首页 > 解决方案 > 如何在 UITableViewCell 中检查 UILabel 是否被截断?

问题描述

我有自动尺寸适合 tableViewCell,以及如何知道它的 UILabel 是否被截断。
我也明白使用我的 UILabel 扩展代码。
请告诉我我的代码有什么问题?
当我滚动表格视图并打印正确的布尔值时。
有什么想法让我在第一次初始化时得到正确的布尔值。
谢谢。

class ViewController: UIViewController {

let itemCount: Int = 10
let tableView = UITableView()
let cellWithButton = "cellWithButton"
var isExpand: Bool = false
var expandingStateArray: [Bool] = []

let textArray: [String] = ["If you read and listen to two articles every day, your reading and listening skills can immm If you read and listen to two articles every day, your reading and listening skills can immm If you read and listen to two articles every day, your reading and listening skills can immm If you read and listen to two articles every day, your reading and listening skills can immm If you read and listen to two articles every day, your reading and listening skills can immm", "If you read and listen to two articles every day", "If you read and listen to two articles every day, your reading and listening skills can immm If you read and listen to two articles every day", "If you read and listen to two articles every day, your reading and listening skills can immm If you read and listen to two articles every day", "If you read and listen to two articles every day, your reading and listening skills can immm If you read and listen to two articles every day", "If you read and listen to two articles every day, your reading and listening skills can immm If you read and listen to two articles every day", "If you read and listen to two articles every day, your reading and listening skills can immm If you read and listen to two articles every day", "If you read and listen to two articles every day, your reading and listening skills can immm If you read and listen to two articles every day", "If you read and listen to two articles every day, your reading and listening skills", "If you read and listen to two articles every day, your reading and listening skills can immm If you read and listen to two articles every day, your reading and listening skills can immm If you read and listen to two articles every day, your reading and listening skills can immm If you read and listen to two articles every day, your reading and listening skills can immm If you read and listen to two articles every day, your reading and listening skills can immm"]

override func viewDidLoad() {
    super.viewDidLoad()

    for _ in 0...itemCount-1 {
        let bool = false
        expandingStateArray.append(bool)
    }

    tableView.delegate = self
    tableView.dataSource = self
    tableView.allowsSelection = false
    tableView.separatorInset = .zero
    tableView.estimatedRowHeight = 44
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.register(WithButtonTableViewCell.self, forCellReuseIdentifier: cellWithButton)

    self.view.addSubview(tableView)

    tableView.snp.makeConstraints { (make) in
        make.top.left.right.bottom.equalToSuperview()
    }
}

@objc func btnPressed(sender: UIButton) {

    let indexPath = IndexPath(row: sender.tag, section: 0)

    if self.isExpand == false {

        self.isExpand = true

        expandingStateArray[sender.tag] = true

    } else {
        self.isExpand = false

        expandingStateArray[sender.tag] = false
    }

    tableView.beginUpdates()
    tableView.reloadRows(at: [indexPath], with: .none)
    tableView.endUpdates()

}  
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return itemCount
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: cellWithButton, for: indexPath) as! WithButtonTableViewCell

    cell.titleLabel.text = textArray[indexPath.row]
    cell.expandButton.addTarget(self, action: #selector(btnPressed), for: .touchUpInside)
    cell.expandButton.tag = indexPath.row

    if expandingStateArray[indexPath.row] {
        cell.titleLabel.numberOfLines = 0
        cell.expandButton.setTitle("Close.", for: .normal)
    }else{
        cell.titleLabel.numberOfLines = 2
        cell.expandButton.setTitle("Show More.", for: .normal)
    }

    print("===) \(indexPath.row) istrun: \(cell.titleLabel.isTruncated)")  //always get true at first time ,when I scroll and get false successfully.

    return cell
}
}

extension UILabel {

func countLabelLines(label: UILabel) -> Int {
    self.layoutIfNeeded()
    let myText = label.text! as NSString

    let rect = CGSize(width: label.bounds.width, height: CGFloat.greatestFiniteMagnitude)
    let labelSize = myText.boundingRect(with: rect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: label.font], context: nil)

    return Int(ceil(CGFloat(labelSize.height) / label.font.lineHeight))
}

var isTruncated: Bool {

    guard let labelText = text else {
        return false
    }

    let labelTextSize = (labelText as NSString).boundingRect(
        with: CGSize(width: frame.size.width, height: .greatestFiniteMagnitude),
        options: .usesLineFragmentOrigin,
        attributes: [.font: font],
        context: nil).size

    return labelTextSize.height > bounds.size.height
}

}

标签: swiftuitableviewuilabel

解决方案


当您第一次显示表格视图时,您不能完全确定单元格的宽度,因为用户可能将 iOS 设备设置为纵向或横向(他们也可以随意旋转它)。

您应该在这里做的是将您的“显示更多”按钮添加到所有单元格,然后根据文本是否被截断来显示或隐藏它。

显示或隐藏该按钮的正确位置是在UITableViewDelegate willDisplay:forRowAt:函数中。

也许是这样的:

func tableView(_ tableView: UITableView, 
            willDisplay cell: UITableViewCell, 
               forRowAt indexPath: IndexPath) 
{
    // previously set the titleLabel to the text in `cellForRowAtIndexPath`
    let labelIsTruncated = cell.titleLabel.isTruncated
    // if label is truncated, isHidden should be false.
    cell.showMoreButton.isHidden = (labelIsTruncated == false)
}

推荐阅读