先设置文字宽度
self.descritionLabel.preferredMaxLayoutWidth = kScreenWidth - 80 - 16
才能获取正确的文字行数,根据行数显示或隐藏按钮
self.showButton.isHidden = descritionLabel.totalOfLines() <= 3 ? true : false
如果有按钮,点击按钮设置状态user.isExpand,根据状态来展开收起文字
self.descritionLabel.numberOfLines = user.isExpand == true ? 0 : 3
extension获得label总行数
/// - Returns: 总行数
func totalOfLines() -> Int {
if let attrText = self.attributedText {
/// 创建CTFrame
let setter: CTFramesetter = CTFramesetterCreateWithAttributedString(attrText)
let path: CGMutablePath = CGMutablePath()
path.addRect(CGRect(x: 0, y: 0, width: self.preferredMaxLayoutWidth, height: CGFloat.greatestFiniteMagnitude))
let frame: CTFrame = CTFramesetterCreateFrame(setter, CFRangeMake(0, 0), path, nil)
/// 获得CTLine数组
let lines = CTFrameGetLines(frame)
//获得行数
let totalOfLines = CFArrayGetCount(lines)
//Logger.log("totalOfLines: \(totalOfLines) :\(attrText.string)")
return totalOfLines
}
return 0
}
网友评论