我正在尝试使用 UITableView 并让单元格内容在用户单击标签时展开或收缩。
但是,我看到的行为是单元格将收缩(例如,我将标签的 numberOfLines 从 0 更改为 1,然后标签将收缩)。但是,当我将标签的 numberOfLines 从 1 更改为 0 时,它不会扩展。
我编写了一个简单的测试程序来显示我遇到的问题。
我正在使用 UITapGestureRecognizer 来处理标签的点击事件,这就是我展开或收缩标签的地方。有谁知道我做错了什么?
这是我的 Storyboard和 View Controller 代码。
import UIKit
class MyCell : UITableViewCell {
@IBOutlet weak var myLabel: UILabel!
}
class TableViewController: UITableViewController {
let cellID = "cell"
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 75
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 12
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "section " + String(section)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 4
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: self.cellID, for: indexPath) as! MyCell
cell.myLabel.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleCellTapped(_:)))
cell.myLabel!.addGestureRecognizer(tapGesture)
// Configure the cell...
if indexPath.row % 2 == 0 {
cell.myLabel?.numberOfLines = 1
cell.myLabel.text = "This is some long text that should be truncated. It should not span over multiple lines. Let's hope this actually works. \(indexPath.row)"
} else {
cell.myLabel?.numberOfLines = 0
cell.myLabel.text = "This is some really, really long text. It should span over multiple lines. Let's hope this actually works. \(indexPath.row)"
}
return cell
}
@objc func handleCellTapped(_ sender: UITapGestureRecognizer) {
print("Inside handleCellTapped...")
guard let label = (sender.view as? UILabel) else { return }
//label.translatesAutoresizingMaskIntoConstraints = false
// expand or contract the cell accordingly
if label.numberOfLines == 0 {
label.numberOfLines = 1
} else {
label.numberOfLines = 0
}
}
}
最佳答案
做两件事。
- 设置垂直内容拥抱优先级并 将标签的垂直内容抗压缩优先级设置为 1000。
- 更改 Label 的行数后,调用 tableView.beginUpdates() 和 tableView.endUpdates()
这肯定有效。
关于ios - 展开和收缩标签在 UITableViewCell 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52133086/