Swift 在UITableViewCell的YYLabel 当字符串外界传入 如果字符串超过三行在第三行的末尾添加全文去掉剩余不用添加点击事件也不需要展开不足三行直接显示
要实现在UITableViewCell的YYLabel中根据字符串的行数进行处理,可以使用YYLabel的numberOfLines属性来限制显示的行数。根据字符串的行数,判断是否超过三行,如果超过三行则在第三行的末尾添加"全文"字样,否则直接显示完整的字符串。
首先,将YYLabel的numberOfLines属性设置为3,这样文本最多只会显示三行。然后根据字符串的行数进行处理,可以使用NSString的boundingRect(with:options:attributes:context:)方法来获取字符串的行数。代码如下:
let label = YYLabel()
label.numberOfLines = 3
// 设置label的文本
label.text = yourString
// 获取label的字体
let font = label.font ?? UIFont.systemFont(ofSize: UIFont.systemFontSize)
// 设置最大宽度为label的宽度
let maxWidth = label.frame.size.width
// 设置行间距
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 5
// 设置字体和行间距
let attributes: [NSAttributedString.Key : Any] = [
.font: font,
.paragraphStyle: paragraphStyle
]
// 计算字符串的高度
let size = (yourString as NSString).boundingRect(with: CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
attributes: attributes,
context: nil)
// 判断字符串的行数是否超过三行
if size.height > font.lineHeight * 3 {
// 获取三行的文本范围
let range = (yourString as NSString).rangeOfComposedCharacterSequences(for: NSMakeRange(0, yourString.count))
// 添加"全文"字样
let fullText = NSMutableAttributedString(string: yourString)
fullText.replaceCharacters(in: range, with: "全文")
// 更新label的文本
label.attributedText = fullText
} else {
// 不超过三行,直接显示完整的字符串
label.text = yourString
}
这样就可以根据字符串的行数在UITableViewCell的YYLabel中进行处理,如果超过三行则在第三行的末尾添加"全文"字样,不超过三行则直接显示完整的字符串。
原文地址: http://www.cveoy.top/t/topic/jbrI 著作权归作者所有。请勿转载和采集!