我有自动调整大小的tableViewCell,以及如何知道UILabel是否被截断。
使用UILabel扩展代码,我也能理解。
请告诉我代码有什么问题?
当我滚动tableview并打印正确的布尔值时。
有什么想法让我在第一次初始化时就得到正确的布尔值。
谢谢。

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
}

}

最佳答案

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

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

And the right place to show or hide that button位于UITableViewDelegate willDisplay:forRowAt: function中。

也许像这样:

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)
}

关于swift - 如何在UITableViewCell中检查UILabel是否被截断?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53920928/

10-11 15:37