swift - UITableViewCell 增加字体大小时更改标签约束

标签 swift uitableview nslayoutconstraint

我想在增加字体大小时更改单元格中的标签顶部和底部约束:

   @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

}

自动单元格高度运行良好,但约束条件没有改变!

最佳答案

来自Apple Documentation :

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/

相关文章:

ios - 跨不同设备的圆形个人资料图片缺少 Xcode 适当的自动布局约束

swift - 试图让拾色器在 Swift 2.0 中工作

ios - UIProgressView - 进度条 - SpriteKit/Swift

ios - 具有动态原型(prototype)内容和多部分的 UITableView

objective-c - 为 UITableView 的 tableFooterView 设置标签 - 使用自动布局

ios - 组件的尾部约束等于其前导约束

ios - 如何获取 2 个不相关的 Swift 对象以了解如何执行相同的函数集

swift - UICollectionView 突出显示带有阴影的单元格

ios - 为什么 insertRowsAtIndexPaths 总是导致 TableView 滚动到顶部?

iphone - 使用搜索显示 Controller 时自定义 CellIdentifier 为空