Swift 在UITableViewCell的YYLabel类型的saylab 当字符串外界传入 如果字符串超过三行在第三行的末尾添加全文去掉剩余不用添加点击事件也不需要展开不足三行直接显示最好封装一个方法
可以通过以下方法来实现:
import UIKit
extension UITableViewCell {
func configureLabelWithText(_ text: String) {
let label = YYLabel()
label.numberOfLines = 3
label.frame = contentView.bounds
contentView.addSubview(label)
let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 15)]
let attributedText = NSAttributedString(string: text, attributes: attributes)
let container = YYTextContainer(size: contentView.bounds.size)
container.maximumNumberOfRows = 3
let layout = YYTextLayout(container: container, text: attributedText)
if layout?.rowCount ?? 0 > 2 {
let truncationToken = NSAttributedString(string: "...全文")
let truncatedText = attributedText.yy_truncated(for: container, truncationToken: truncationToken)
label.attributedText = truncatedText
} else {
label.attributedText = attributedText
}
}
}
使用方法:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! UITableViewCell
let text = "这是一个超过三行的字符串文本,应该在第三行的末尾添加全文,并去掉剩余部分。"
cell.configureLabelWithText(text)
return cell
}
在上述示例中,我们创建了一个UITableViewCell的扩展,其中的configureLabelWithText方法用于配置YYLabel并根据字符串内容进行布局。首先,我们将YYLabel添加到cell的contentView中,并设置其行数为3。然后,根据传入的字符串创建NSAttributedString,并使用YYTextContainer和YYTextLayout来计算文本的布局。如果布局的行数超过2行(即超过三行),我们使用yy_truncated方法添加省略号和全文文本,然后将结果设置为YYLabel的attributedText。如果布局的行数不超过2行,则直接将NSAttributedString设置为YYLabel的attributedText。
原文地址: http://www.cveoy.top/t/topic/jbrP 著作权归作者所有。请勿转载和采集!