UITableViewCell的布局约束未更新

时间:2020-09-06 19:18:18

标签: ios swift uitableview autolayout

我要实现的效果是使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,则一切正常。

1 个答案:

答案 0 :(得分:1)

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