2014-11-05 65 views
2

我已經子類化了一個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

回答

1

爲什麼不改變常量而不是刪除和重新添加約束?

cell.usernameConstraint.constant = topDistance; 
+0

我正在嘗試這個,但約束不會改變 – 2016-04-09 12:26:35

+0

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