我想在增加字体大小时更改单元格中的标签顶部和底部约束:
@IBAction func changeFontSize(_ sender: UIBarButtonItem) {
fontSize += 2
self.tableView.reloadData()
self.tableView.reloadInputViews()
self.tableView.setNeedsUpdateConstraints()
}
在单元格中:
cellLabel.numberOfLines = 0
cellLabel.sizeToFit()
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableCells
let cellTitle = dataArray.object(at: indexPath.row) as! NSString
cell.cellLabel.attributedText = self.convertStringToAttributeText(text: cellTitle)
let paragraphSpace = fontSize / 3
cell.cellLabel.translatesAutoresizingMaskIntoConstraints = false
let hConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[label]-20-|", options: .init(rawValue: 0), metrics: nil, views: ["label": cell.cellLabel])
cell.contentView.addConstraints(hConstraints)
let vConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-\(paragraphSpace)-[label]-\(paragraphSpace)-|", options: .init(rawValue: 0), metrics: nil, views: ["label": cell.cellLabel])
cell.contentView.addConstraints(vConstraints)
return cell
}
自动单元格高度运行良好,但约束条件没有改变!
最佳答案
When developing for iOS 8.0 or later, use the NSLayoutConstraint class’s activate(:) method instead of calling the addConstraints(:) method directly. The activate(_:) method automatically adds the constraints to the correct views.
此外,我建议在单元格的子类中重写 updateConstraints()
,而不是在每次使用单元格时删除并重新创建约束。
关于swift - UITableViewCell 增加字体大小时更改标签约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48276037/