我有一个像动态字符串这样的数据。
我想检查这个字符串是否超出了我的标签宽度,其中 numberOfLines
等于 1。
如果超出我的标签宽度,我会使用 cellA
。
如果不超出我的标签宽度,我会使用 cellB
。
我的观点是如何检查和更改“isLongName” bool 值。
对我有什么建议吗?
var isLongName: Bool = false
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// How to check the string is long name (width out of cellB)
if isLongName && indexPath.row == 3 {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCellA", for: indexPath) as! TableViewCellA
cell.titleLabel.text = itemsArray[indexPath.row].title
cell.subtitleLabel.text = itemsArray[indexPath.row].value
cell.expandBtn.addTarget(self, action: #selector(expandBtnPressed), for: .touchUpInside)
cell.expandBtn.tag = indexPath.row
if isExpand {
cell.expandBtn.setTitle("close", for: .normal)
cell.subtitleLabel.numberOfLines = 0
} else {
cell.expandBtn.setTitle("open", for: .normal)
cell.subtitleLabel.numberOfLines = 1
}
cell.remakeLayout(isExpand: isExpand)
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCellB", for: indexPath) as! TableViewCellB
cell.titleLabel.text = itemsArray[indexPath.row].title
cell.subtitleLabel.text = itemsArray[indexPath.row].value
return cell
}
}
@objc func expandBtnPressed(sender: UIButton) {
let indexPath = IndexPath(row: sender.tag, section: 0)
UIView.performWithoutAnimation {
tableView.beginUpdates()
self.isExpand = !isExpand
tableView.reloadRows(at: [indexPath], with: .none)
tableView.endUpdates()
}
}
最佳答案
添加以下UILabel扩展
extension UILabel {
func calculateMaxLines() -> Int {
let maxSize = CGSize(width: frame.size.width, height: CGFloat(Float.infinity))
let charSize = font.lineHeight
let text = (self.text ?? "") as NSString
let textSize = text.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
let linesRoundedUp = Int(ceil(textSize.height/charSize))
return linesRoundedUp
}
}
将文本分配给UIlabel
后检查所需的行数。如果您从 calculateMaxLines
得到结果 1,则不需要显示更多按钮。
cell.subtitleLabel.text = itemsArray[indexPath.row].value
print("number of line required: ",cell.subtitleLabel.calculateMaxLines())
关于ios - 如何检查 UITableViewCell 标签是否被截断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56592431/