Swift UITableViewCell中使用YYLabel限制行数并添加“全文”显示
你可以封装一个方法来实现这个需求。以下是一个可能的实现:
import UIKit
import YYText
extension UITableViewCell {
func configureYYLabelWithLimitedLines(text: String, maxLines: Int) {
let label = YYLabel()
label.numberOfLines = maxLines
label.frame = contentView.bounds
contentView.addSubview(label)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byTruncatingTail
paragraphStyle.alignment = .left
let attributedText = NSAttributedString(string: text,
attributes: [
.font: label.font,
.paragraphStyle: paragraphStyle
])
label.attributedText = attributedText
let layoutManager = YYTextLayout(containerSize: label.bounds.size)
layoutManager.setAttributedString(attributedText)
let linesCount = layoutManager.numberOfLines()
if linesCount > maxLines {
let truncationToken = NSAttributedString(string: '全文')
let range = NSRange(location: attributedText.length - truncationToken.length, length: truncationToken.length)
let truncatedText = NSMutableAttributedString(attributedString: attributedText.attributedSubstring(from: NSMakeRange(0, range.location)))
truncatedText.append(truncationToken)
label.attributedText = truncatedText
}
}
}
然后在你的UITableViewCell子类中调用这个方法来配置YYLabel:
class MyTableViewCell: UITableViewCell {
func configureCell(withText text: String) {
configureYYLabelWithLimitedLines(text: text, maxLines: 3)
}
}
使用示例:
let cell = MyTableViewCell(style: .default, reuseIdentifier: "MyCell")
let text = "这是一个超过三行的字符串,它将被截断并在第三行末尾添加‘全文’"
cell.configureCell(withText: text)
这样,如果字符串超过三行,它将被截断并在第三行末尾添加‘全文’,如果不超过三行,它将直接显示。
原文地址: https://www.cveoy.top/t/topic/hXrg 著作权归作者所有。请勿转载和采集!