iOSanimationUILabel展开
我有一个UILabel,由3行文本启动:
locationDescription = [[UILabel alloc]init]; locationDescription.numberOfLines = 3; [locationDescription setTranslatesAutoresizingMaskIntoConstraints:NO]; [self addSubview:locationDescription];
然后我有一个扩展标签的button:
- (void)buttonPressed:(UIButton *)sender{ NSLog(@"Pressed"); [UIView animateWithDuration:1 animations:^{locationDescription.numberOfLines = 0;} ]; }
标签的理想行为是让每条额外的线条一次一个地显示出来。 标签扩展得很好,但过渡不是animation,所有的线条都立刻显现出来。
我错过了什么?
您可以animation多行。 它改变了UILabel
的内在大小。 您需要在包含UILabel的视图上的animation块内调用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() } } }
你不能animation多行,你应该animation的大小,并从一开始就设置行数为0。
我不添加高度计算代码,因为它会隐藏真实的animation。
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.
前面。
UIView animateWithDuration的块对象包含提交到视图的更改。 这是以编程方式更改视图层次结构中视图的任何animation属性的位置。 但是您指定的属性numberOfLines不是animation属性。
作为UILabel的父类的UIView类的以下属性是可以animation的:
@property frame @property bounds @property center @property transform @property alpha @property backgroundColor @property contentStretch