Swift 在UITableViewCell的YYLabel类型的saylab 当字符串外界传入 如果字符串超过三行在第三行的末尾添加全文去掉剩余不用添加点击事件也不需要展开不足三行直接显示封装一个方法
可以封装一个方法来实现这个需求,以下是一个可能的实现方式:
import UIKit
import YYKit // 需要引入YYKit库
extension UITableViewCell {
func configureLabel(withText text: String) {
let label = YYLabel()
label.numberOfLines = 3
label.frame = CGRect(x: 0, y: 0, width: contentView.frame.width, height: contentView.frame.height)
contentView.addSubview(label)
let attributeText = NSMutableAttributedString(string: text)
attributeText.font = UIFont.systemFont(ofSize: 14)
attributeText.lineBreakMode = .byTruncatingTail
let container = YYTextContainer(size: CGSize(width: label.frame.width, height: CGFloat.greatestFiniteMagnitude))
let layout = YYTextLayout(container: container, text: attributeText)
if layout?.rowCount ?? 0 > 3 {
let truncationToken = NSAttributedString(string: "全文")
attributeText.append(truncationToken)
let truncationRange = NSRange(location: layout!.visibleRange.length - truncationToken.length, length: truncationToken.length)
attributeText.setTextHighlight(truncationRange, color: nil, backgroundColor: nil, userInfo: nil, tapAction: nil, longPressAction: nil)
label.truncationToken = truncationToken
}
label.attributedText = attributeText
}
}
这样,你可以在你的 UITableViewCell 的子类中调用 configureLabel(withText:) 方法来设置 YYLabel 的显示文本。如果文本超过三行,会在第三行的末尾添加"全文"。如果文本不足三行,会直接显示文本内容。
原文地址: http://www.cveoy.top/t/topic/jbrW 著作权归作者所有。请勿转载和采集!