你可以通过扩展 UITableViewCell 来实现这个功能。首先,创建一个名为'UITableViewCell+YYLabelExtension.swift' 的文件,然后在其中添加以下代码:

import UIKit
import YYText

extension UITableViewCell {
    
    func configureYYLabel(with text: String) {
        let label = YYLabel()
        label.numberOfLines = 3
        label.textVerticalAlignment = .top
        label.preferredMaxLayoutWidth = UIScreen.main.bounds.width - 16 // 根据需要设置合适的宽度
        
        let attributedText = NSMutableAttributedString(string: text)
        let font = UIFont.systemFont(ofSize: 14) // 根据需要设置合适的字体大小
        attributedText.yy_font = font
        
        let layoutManager = NSLayoutManager()
        let textContainer = YYTextContainer(size: CGSize(width: label.preferredMaxLayoutWidth, height: CGFloat.greatestFiniteMagnitude))
        let textStorage = YYTextStorage(attributedString: attributedText)
        textStorage.addLayoutManager(layoutManager)
        layoutManager.addTextContainer(textContainer)
        
        let range = NSRange(location: 0, length: attributedText.length)
        let rect = layoutManager.usedRect(for: textContainer)
        
        if rect.height > label.font.lineHeight * 3 {
            let truncatedString = NSMutableAttributedString(string: text)
            let truncatedRange = NSRange(location: text.count - 2, length: 2) // 添加'全文'字符串
            let truncatedAttributes = [
                NSAttributedString.Key.font: font,
                NSAttributedString.Key.foregroundColor: UIColor.blue, // 自定义颜色
                NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue
            ]
            truncatedString.replaceCharacters(in: truncatedRange, with: NSAttributedString(string: '全文', attributes: truncatedAttributes))
            label.attributedText = truncatedString
        } else {
            label.attributedText = attributedText
        }
        
        label.frame = CGRect(x: 8, y: 8, width: label.preferredMaxLayoutWidth, height: rect.height)
        contentView.addSubview(label)
    }
}

然后,在你的 UITableViewCell 子类中调用该方法即可。例如:

class CustomTableViewCell: UITableViewCell {
    
    func configureCell(with text: String) {
        configureYYLabel(with: text)
    }
}

这样,当你在 UITableViewdataSource 方法中配置单元格时,只需调用 configureCell(with:) 方法即可实现对 YYLabel 的配置。

Swift UITableViewCell YYLabel 超过三行显示 '全文' 的优雅实现

原文地址: https://www.cveoy.top/t/topic/hXwk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录