【问题标题】:Layout constraint not updating for UITableViewCellUITableViewCell 的布局约束未更新
【发布时间】:2020-12-25 07:28:35
【问题描述】:

我想要达到的效果是让它感觉就像 UITableViewCell 在被选中时“变宽”了一样。为此,我向 UITableViewCell 的内容视图添加了一个子视图(我们称之为 visibleView),然后在选择单元格时调整 mainView。

但是,visibleView 的大小在选择时不会改变。代码如下:

class feedTableCell: UITableViewCell {
    
    var visibleCell: UIView!
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.backgroundColor = .clear
        
        self.visibleCell = UIView()
        self.visibleCell.translatesAutoresizingMaskIntoConstraints = false
        
        self.contentView.addSubview(self.visibleCell)
        
        visibleCell.widthAnchor.constraint(equalToConstant: 150).isActive = true
        visibleCell.heightAnchor.constraint(equalToConstant: 100).isActive = true
        visibleCell.centerXAnchor.constraint(equalTo: self.contentView.centerXAnchor).isActive = true
        visibleCell.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor).isActive = true
        
        visibleCell.layer.cornerRadius = 15
        visibleCell.backgroundColor = .white
        
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        
        if selected {
            self.visibleCell.widthAnchor.constraint(equalToConstant: 300).isActive = true
            self.contentView.layoutIfNeeded()
        } else {            
            self.visibleCell.widthAnchor.constraint(equalToConstant: 150).isActive = true
            self.contentView.layoutIfNeeded()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

但是,如果我用框架替换布局约束,而是通过调整其框架来更新 visibleCell,一切正常。

【问题讨论】:

  • 您必须先删除之前的宽度限制,然后才能添加新的限制。它们不被交换。保留对约束的引用,以便在添加新约束之前能够将其删除。
  • 谢谢!我没有意识到布局约束不是那样工作的。请作为官方答案提交,以便我将其标记为正确。

标签: ios swift uitableview autolayout


【解决方案1】:

在添加新的之前,您必须删除之前的宽度限制。它们不被交换。在添加新约束之前,保留对约束的引用以便能够将其删除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多