SwiftYYLabel如果字符串超过三行在第三行的末尾添加全文不用添加点击事件也不需要展开要在UITableViewCell字符串外界传入
在 UITableViewCell 中使用 Swift 和 YYLabel 进行字符串展示,并在第三行的末尾添加全文内容,可以按照以下步骤进行操作:
-
首先,确保已经导入了 YYText 框架,可以通过 Cocoapods 进行安装。
-
在 UITableViewCell 的类中,添加一个 YYLabel 的实例变量,用于展示字符串内容。
import UIKit
import YYText
class CustomTableViewCell: UITableViewCell {
var contentLabel: YYLabel!
// 其他代码...
}
- 在 UITableViewCell 的初始化方法中,对 contentLabel 进行初始化,并设置其相关属性。
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// 初始化 contentLabel
contentLabel = YYLabel()
contentLabel.numberOfLines = 3
contentLabel.font = UIFont.systemFont(ofSize: 14)
// 添加 contentLabel 到 cell 上
contentView.addSubview(contentLabel)
// 设置 contentLabel 的约束
contentLabel.translatesAutoresizingMaskIntoConstraints = false
contentLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
contentLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10).isActive = true
contentLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
contentLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10).isActive = true
}
- 在 UITableViewCell 的数据源方法中,根据传入的字符串内容,设置 contentLabel 的文本。
func configureCell(with text: String) {
contentLabel.textLayout = nil
let textContainer = YYTextContainer(size: CGSize(width: contentView.bounds.width - 20, height: CGFloat.greatestFiniteMagnitude))
let textLayout = YYTextLayout(container: textContainer, text: NSAttributedString(string: text))
if textLayout?.rowCount ?? 0 > 3 {
let truncatedString = NSAttributedString(string: "全文")
let truncatedText = NSMutableAttributedString(attributedString: textLayout!.text)
truncatedText.append(truncatedString)
contentLabel.attributedText = truncatedText
} else {
contentLabel.attributedText = textLayout?.text
}
}
- 在 UITableViewController 的数据源方法中,调用 configureCell 方法进行 UITableViewCell 的配置。
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
// 根据数据源中的字符串设置 cell 的内容
let text = dataSource[indexPath.row].text
cell.configureCell(with: text)
return cell
}
这样,当字符串的行数超过 3 行时,contentLabel 的文本会在第三行的末尾添加 "全文"。不需要添加点击事件和展开操作,即可实现要求。
原文地址: http://www.cveoy.top/t/topic/jbrA 著作权归作者所有。请勿转载和采集!