动画到文本高度(自动布局)

Animate to text height (autolayout)

我想从 0 的高度到文本 (UILabel) 的高度设置动画。我正在使用自动版式,但我不知道文本的高度。我的方法是首先为文本设置一个 height=0 约束,然后像这样设置动画:

//retrieves the height constrain of the clicked item
NSLayoutConstraint *heightContraint = [heightConstraints objectAtIndex:sender.tag];
//activates/deactivates the constraint
heightContraint.active = !heightContraint.active;
//animates
[UIView animateWithDuration:3 animations:^{
    [self layoutIfNeeded];
}];

我的问题是,使用这种方法,文本高度不会设置动画,它会立即从 0 高度变为新高度。只有包含视图的 position/size 更改是动画的。如何在不知道文本高度的情况下为文本高度变化设置动画?

我找到了解决办法。我没有设置高度约束,而是设置了一个包含视图(剪辑),其中包含 UILabel 和上面的视图。然后,我创建了 2 个约束,将底部边缘固定到包含视图,一个与 UILabel 相关,一个与上面的视图相关。我只是 activate/deactivate 像这样的约束:

//get the constraints
NSLayoutConstraint *viewAboveTextConstraint = 
        [viewAboveTextConstraints objectAtIndex:sender.tag];
NSLayoutConstraint *uilabelContraint = [uilabelContraints objectAtIndex:sender.tag];
//flip the active states
viewAboveTextConstraint.active = !viewAboveTextConstraint.active;
uilabelContraint.active = !uilabelContraint.active;
//animate
[UIView animateWithDuration:.3 animations:^{           
        [self layoutIfNeeded];
}];