首页 > 解决方案 > UITableViewCell 的布局约束未更新

问题描述

我想要达到的效果是让它感觉就像 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,一切正常。

标签: iosswiftuitableviewautolayout

解决方案


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


推荐阅读