在我的 iPhone 应用程序中,我有一个多行标签,我想用“更多”按钮扩展/收缩它。像这样:
Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Donec fringilla, turpis
in porttitor imperdiet, eros turpis...
"<More>"
应该为此设置动画:
Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Donec fringilla, turpis
in porttitor imperdiet, eros turpis laoreet
magna, id tempor ante lorem pulvinar lacus.
Duis vitae nisl quis sapien dictum pellentesque.
"<Less>"
我试图获得一种效果,即随着标签的增长,每一行都单独显示,然后随着标签的缩小而单独隐藏。增长效果很好,但在收缩动画期间它会跳到 3 行。有任何想法吗?以下代码和属性:
成长动画:
[UIView animateWithDuration:0.5 animations:^{
view.frame = CGRectMake(startFrame.origin.x, startFrame.origin.y, startFrame.size.width, startFrame.size.height + 40.0);
}];
收缩动画:
[UIView animateWithDuration:0.5 animations:^{
view.frame = CGRectMake(startFrame.origin.x, startFrame.origin.y, startFrame.size.width, startFrame.size.height - 40.0);
}];
UILabel 属性:
- 行数:0
- 换行符:截尾
- 内容模式:置顶
最佳答案
您可以通过使用自动布局约束并将 numberOfLines 从 3 修改为 0 来为其设置动画。(0 是一个特殊值,表示显示任意数量的行)。
标签有一个固有的大小,当你修改 numberOfLines 时它会改变,这些会影响约束。代码如下所示:
@IBAction func buttonTapped(sender: UIButton) {
let numberOfLines = label.numberOfLines == 0 ? 3 : 0
label.numberOfLines = numberOfLines
let newTitle = numberOfLines == 0 ? "Less" : "More"
sender.setTitle(newTitle, forState: .Normal)
UIView.animateWithDuration(0.5) { self.view.layoutIfNeeded() }
}
您需要告诉包含标签和按钮的 View 它需要在动画 block 中进行布局。
关于iphone - 扩展多行 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10761526/