iphone - 扩展多行 UILabel

标签 iphone objective-c ios xcode

在我的 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 中进行布局。

enter image description here

关于iphone - 扩展多行 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10761526/

相关文章:

iphone - 推送 View Controller 时应用程序崩溃,[NSConcreteData initWithContentsOfURL :options:error:]: nil URL argument'

ios - 无法将数据填充到 TableView 中

iphone - 哪些对象添加到self.view后可以立即释放

ios - 将移除 navigationBar 边框转换为 swift

iphone - 在iphone中从数据库中读取图像的问题

iphone - Grand Central Dispatch 函数调用

ios - json 格式的顺序正在改变

c++ - macOS 中的 CMake,预编译头文件 (.pch) 支持

ios - 我将如何在 Swift 中重写这个 Objective-C 策略模式?

ios - Objective-C:复制和删除文件(文件管理器)