2013-08-29 4 views
1

У меня есть пользовательский UITableViewCell с тремя ярлыками - заголовок, субтитры и правильная деталь. Теперь, когда пользователь нажимает на ячейку, эта ячейка становится стандартной с Checkmark, но мне нужно анимировать правую метку слева. Я думал, что могу просто сделатьАнимация UILabel в UITableViewCell

CGRect rect = cell.playerRatingLabel.frame; 
rect.origin.x -= 10; 
[CLCPlayerViewCell animateWithDuration:1.0 animations:^{ 
    cell.playerRatingLabel.frame = rect; 
}]; 

но это, кажется, ничего не делает. Я думаю, что это касается ограничений, но я не знаю, как с этим справиться, я использую автоматический макет.

Спасибо за любую помощь

ответ

3

Ваш плеер RatingLabel должен иметь ограничение на правый край ячейки. Ваша пользовательская ячейка должна сделать IBOutlet для этого ограничения. Затем на мобильный кран, анимировать постоянный параметр этого ограничения (я назвал выход rightCon в примере):

[UIView animateWithDuration:1.0 animations:^{ 
    cell.rightCon.constant = 30; // change this value to meet your needs 
    [cell layoutIfNeeded]; 
}]; 

Вот полная реализация, что я использую, чтобы сделать это. Моя пользовательская ячейка имела две метки, и я анимация правой, когда вы нажимаете на ячейку и добавляете галочку. Я создал свойство selectedPaths (изменяемый массив), чтобы отслеживать проверенные ячейки. Если вы нажмете на ячейку, которая уже проверена, она отменяет ее и оживляет этикетку в исходное положение.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    RDCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 
    cell.leftLabel.text = self.theData[indexPath.row]; 
    cell.accessoryType = ([self.selectedPaths containsObject:indexPath])? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone; 
    cell.rightCon.constant = ([self.selectedPaths containsObject:indexPath])? 40 : 8; 
    return cell; 
} 


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
    RDCell *cell = (RDCell *)[tableView cellForRowAtIndexPath:indexPath]; 
    if (! [self.selectedPaths containsObject:indexPath]) { 
     [self.selectedPaths addObject:indexPath]; 
     cell.accessoryType = UITableViewCellAccessoryCheckmark; 
     [UIView animateWithDuration:.3 animations:^{ 
      cell.rightCon.constant = 40; 
      [cell layoutIfNeeded]; 
     }]; 
    }else{ 
     [self.selectedPaths removeObject:indexPath]; 
     cell.accessoryType = UITableViewCellAccessoryNone; 
     [UIView animateWithDuration:.3 animations:^{ 
      cell.rightCon.constant = 8; 
      [cell layoutIfNeeded]; 
     }]; 
    } 
} 
+0

Действительно. Наконец, ответ, который не требует манипуляции с кадрами, который не очень устойчив при работе с макетом. – Abizern

+0

очень приятный ответ спасибо, я думал о Constraints, но не знал, что могу настроить Outlet to Constraint, теперь я узнал :) – user1396236

+0

@ user1396236, я добавил к своему ответу, чтобы показать, как я сделал включая отмену проверки ячеек, если вы нажмете на них снова. – rdelmar

0

Вы пытаетесь настроить рамку ячейки, которая не будет иметь никакого эффекта. Попробуйте настроить рамку ячейки contentView.

0

я думаю, следующая функция будет решить вашу проблему передать свой ярлык, как cell.textLabel.layer и ден пройти точку, как

CGPointMake(0, self.view.center.y) 

-(void)moveLayer:(CALayer*)layer to:(CGPoint)point 
{ 
// Prepare the animation from the current position to the new position 
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"]; 
animation.fromValue = [layer valueForKey:@"position"]; 
animation.duration = 0.2; 

animation.toValue = [NSValue valueWithCGPoint:point]; 

// Update the layer's position so that the layer doesn't snap back when the animation completes. 
layer.position = point; 

// Add the animation, overriding the implicit animation. 
[layer addAnimation:animation forKey:@"position"]; 
}