Swift UITableViewCell 中的 YYLabel 文本截断显示:三行限制,末尾添加 '全文'
Swift UITableViewCell 中的 YYLabel 文本截断显示:三行限制,末尾添加 '全文'
本文将介绍如何在 Swift 中使用 YYLabel 在 UITableViewCell 中实现三行文本截断显示,超过三行则在末尾添加 '全文',不足三行则直接显示。
代码实现
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 的显示文本。如果文本超过三行,会在第三行的末尾添加 '全文'。如果文本不足三行,会直接显示文本内容。
原文地址: https://www.cveoy.top/t/topic/hXoX 著作权归作者所有。请勿转载和采集!