iOS动画UILabel扩展

时间:2014-01-06 19:57:58

标签: ios uilabel core-animation

我有一个用3行文字启动的UILabel:

locationDescription = [[UILabel alloc]init];
locationDescription.numberOfLines = 3;
[locationDescription setTranslatesAutoresizingMaskIntoConstraints:NO];
[self addSubview:locationDescription];

然后我有一个扩展标签的按钮:

- (void)buttonPressed:(UIButton *)sender{
    NSLog(@"Pressed");
    [UIView animateWithDuration:1
                     animations:^{locationDescription.numberOfLines = 0;}
     ];
}

标签的理想行为是让每个额外的行一次显示一个。标签扩展正常,但转换不是动画,所有行都只是一次显示。

我错过了什么?

3 个答案:

答案 0 :(得分:14)

您可以为行数设置动画。它会更改UILabel的intrinsicSize。您需要在包含UILabel的视图中的动画块内调用layoutIfNeeded。在这里,我将一个轻击手势附加到表格,以便在0(您想要的数量)行和1行之间进行切换。

 func tapLabel(tapGesture: UITapGestureRecognizer)
 {
    if let label = tapGesture.view as? UILabel {
      label.numberOfLines = label.numberOfLines == 0 ? 1 : 0
      UIView.animateWithDuration(0.5) {
        label.superview?.layoutIfNeeded()
      }
    }
 }

enter image description here

答案 1 :(得分:2)

你不能为行数设置动画,你应该设置动画大小,并从一开始就将行数设置为0。

我没有添加高度计算代码,因为它会隐藏真实的动画。

self.locationDescription = [[UILabel alloc] init];
self.locationDescription.numberOfLines = 0;
[locationDescription setTranslatesAutoresizingMaskIntoConstraints:NO];

// Say, it starts with 50. In your real code, height should be calculated
// to fit the size you want, rounded to lines
NSDictionary *viewsDict = @{@"locationDescription": self.locationDescription};
[self.locationDescription addConstraints:
 [NSLayoutConstraint constraintsWithVisualFormat:@"V:[locationDescription(50)]"
                                         options:0 metrics:nil
                                           views:viewsDict];

然后在行动中,做

- (void)buttonPressed:(UIButton *)sender
{
    NSLog(@"Pressed");
    // Assuming there is only one constraint. If not, assign it to another property
    // I put 500, but, again, real size rounded to line height should be here
    self.locationDescription.constraints[0].constant = 500;
    [UIView animateWithDuration:1 animations:^{
        // Layouting superview, as its frame can be updated because of a new size
        [self.locationDescription.superview layoutIfNeeded];
    }];
}

此外,您应该将locationDescription分配给某个媒体资源,并使用前面的self.进行访问。

答案 2 :(得分:2)

UIView animateWithDuration的块对象包含提交视图的更改。这是您以编程方式更改视图层次结构中视图的任何可动画属性的位置。但是您指定的属性numberOfLines不是可动画的属性。

UIVabel父类的UIView类的以下属性是可动画的:

 @property frame
 @property bounds
 @property center
 @property transform
 @property alpha
 @property backgroundColor
 @property contentStretch