更改表格单元格在运行时的自动布局约束

问题描述:

我已经子类化了一个UITableViewCell,它有一堆按钮和在IB中创建的标签,它们都有插座。我想要做的是,根据单元格的内容,UIButton需要稍微向上移动,或者保持原位。我为需要改变的约束创建了一个出口,以便我可以在代码中进行更改。更改表格单元格在运行时的自动布局约束

里面cellForRowAtIndexPath,我有以下几点:

[cell.usernameButton.superview removeConstraint:cell.usernameTopConstraint]; 
int topDistance; 
// code to conditionally change topDistance for constraint is omitted here, results in either 5 or 15 

cell.usernameTopConstraint = [NSLayoutConstraint constraintWithItem:cell.usernameButton 
                   attribute:NSLayoutAttributeTop 
                   relatedBy:NSLayoutRelationEqual 
                    toItem:cell.usernameButton.superview 
                   attribute:NSLayoutAttributeTop 
                   multiplier:1 
                   constant:topDistance]; 

[cell.usernameButton.superview addConstraint:cell.usernameTopConstraint]; 
[cell.usernameButton.superview layoutIfNeeded]; 

问题是,现有的约束不能得到删除,因为我得到的错误:“无法同时满足约束条件” - 两个它为我是可以在上面应用的两个。

奇怪的是,当我登录cell.usernameButton.superview时,对于每个单元格都是空的,直到引入约束错误的非默认topDistance的单元格为止。然后它为后面的每个单元格设置。

为什么约束不被删除?我已经尝试了一系列引用按钮的超级视图的不同方式,其中没有一个可以工作。

+1

为什么不改变常量而不是删除和重新添加约束? – jrturton 2014-11-05 19:48:33

+0

@jturton工作。我试图通过重新定义完全没有用的约束来做到这一点。但我通过'cell.usernameConstraint.constant = topDistance'试过,并且工作正常。谨慎添加这个答案?我会接受。 – inorganik 2014-11-05 20:28:47

+0

我仍然好奇为什么我不能删除约束.... – inorganik 2014-11-05 20:50:35

为什么不改变常量而不是删除和重新添加约束?

cell.usernameConstraint.constant = topDistance; 
+0

我正在尝试这个,但约束不会改变 – 2016-04-09 12:26:35

+0

@MANCHIKANTIKRISHNAKISHORE调用'layoutIfNeeded' – inorganik 2017-07-24 15:03:36