如何检查UITableViewCell中的UILabel是否被截断?

时间:2018-12-25 09:11:42

标签: swift uitableview 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
}

}

1 个答案:

答案 0 :(得分:0)

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

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

And the right place to show or hide that buttonUITableViewDelegate 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)
}