使用 Swift 3 阅读更多/更少 [英] Read More/Less with Swift 3
问题描述
我想在段落末尾添加阅读更多".当我点击阅读更多"文本时,它应该展开并在末尾显示更少".单击较少"文本时,文本将折叠.
I want to add "Read more" at the end of the paragraph. When I click on the "Read more" text, it should be expand and display "Less" at the end.
The texts will be collapsed when click on "Less" text.
我在谷歌找到了很多示例工作.但是,我不太明白,大多数项目都是用Objective-C实现的.我也在youtube上找到了.
我想知道使用 Swift 3 实现此功能的非常示例代码.
我可以在不使用任何额外库的情况下实现吗?
请帮帮我.
I find many sample work in google. But, I don't understand clearly and most projects are implemented with Objective-C. I also find it in youtube.
I would like know very sample code to implement this with Swift 3.
Can I implement without using any additional library?
Please help me.
推荐答案
- 为
messageLabel
的高度限制创建一个出口 - 将阅读更多"按钮的顶部布局设置为
messageLabel
点击阅读更多"按钮增加高度约束常数,点击阅读更少"减少高度约束常数.
- Create an outlet for height constraint of your
messageLabel
- Set top layout of your "Read more" button to
messageLabel
On clicking "Read more" button increase height constraint constant, on clicking "Read less" decrease height constraint constant.
@IBOutlet weak var btn: UIButton! @IBOutlet weak var lblHeight: NSLayoutConstraint! var isLabelAtMaxHeight = false @IBAction func btnAction(_ sender: Any) { if isLabelAtMaxHeight { btn.setTitle("Read more", for: .normal) isLabelAtMaxHeight = false lblHeight.constant = 70 } else { btn.setTitle("Read less", for: .normal) isLabelAtMaxHeight = true lblHeight.constant = getLabelHeight(text: yourSummaryText, width: view.bounds.width, font: yourSummaryLabel.font) } }
获取文本高度
func getLabelHeight(text: String, width: CGFloat, font: UIFont) -> CGFloat { let lbl = UILabel(frame: .zero) lbl.frame.size.width = width lbl.font = font lbl.numberOfLines = 0 lbl.text = text lbl.sizeToFit() return lbl.frame.size.height }
这篇关于使用 Swift 3 阅读更多/更少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Create an outlet for height constraint of your