2017-08-20 16 views
0

我有一個自我尺寸的tableViewCell,它提供註釋。如果當前用戶評論我呈現編輯和刪除按鈕。在這種情況下,我的禁忌是完美的。我所有的約束都是在Interface Builder中設置的。如何在接口生成器中使用自動佈局設置UITableViewCell的自我尺寸限制

現在的挑戰是,當評論不屬於用戶時,我爲編輯和刪除按鈕設置了.isHidden = true。如何調整我對這個新場景的限制?

enter image description here

編輯:問題是,當我設置.isHidden爲true的按鈕,我想單元格高度收縮的按鈕空間是空的。

+0

按鈕是基於值顯示還是隱藏?或者是否有可能會顯示它們,然後在發生其他事情後隱藏?也就是說,當你在'cellForRowAt'中時,當你確定是否顯示或者隱藏按鈕時,它是*那*。 – DonMag

+0

是的DonMag在cellForRowAt ..我檢查:如果comment.userID == appUserID。 如果評論屬於用戶我顯示的按鈕,否則我隱藏它們。 –

回答

1

的另一種方法:

切換從所述按鈕的底部到電池的底部約束的​​狀態下,與.isHidden狀態一起。

要做到這一點,從您date標籤的底部添加一個垂直空間約束細胞的底部,設置爲>= 4(或不過多「填充」您希望在按鈕不存在)。

將從編輯按鈕底部到單元格底部的間距約束添加一個@IBOutlet。在你的圖片中,它顯示爲bottom = Edit Button.bottom + 2。當你按Ctrl + IB,從約束拖動到你的源文件時,它會生成IBOutlet中一行:

@IBOutlet weak var editButtonBottomConstraint: NSLayoutConstraint! 

您需要編輯該行,但...約束被釋放時停用,除非你有一個「強」的參考。因此,只要將weak修改:

@IBOutlet var editButtonBottomConstraint: NSLayoutConstraint! 

現在,在cellForRowAt,你可以這樣做:

cell.deleteButton.isHidden = !(comment.userID == appUserID) 
    cell.editButton.isHidden = !(comment.userID == appUserID) 
    cell.editButtonBottomConstraint.isActive = (comment.userID == appUserID) 

雖然,就個人而言,我會作出這樣的細胞內的功能。


根據你的設計,不過,我猜commentsLabel是可能/可能是一個多行標籤?如果評論是8行,那麼你會希望單元格垂直擴展?如果是這樣,你仍然有一些約束關係可以解決。

1

你可以這樣說:

而是隱藏buttons的,您可以:

設置UIButtontitlenil

2.採取的IBOutletUIButtonheight constraint,只要你想隱藏按鈕,將其設置爲0

實施例:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
{ 
    return 2 
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{ 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableCell 
    if indexPath.row == 1 
    { 
     cell.button.setTitle(nil, for: .normal) 
     cell.buttonHeightConstraint.constant = 0 
    } 
    return cell 
} 

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat 
{ 
    return UITableViewAutomaticDimension 
} 

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat 
{ 
    return UITableViewAutomaticDimension 
} 

定製UITableViewCell

class TableCell: UITableViewCell 
{ 
    @IBOutlet weak var button: UIButton! 
    @IBOutlet weak var buttonHeightConstraint: NSLayoutConstraint! 
} 

截圖:

enter image description here

這將根據您的要求處理約束。

+0

快速註釋...當使用自動調整大小的單元格時,您不應該實現'func tableView(_ tableView:UITableView,heightForRowAt indexPath:IndexPath) - 只需在'viewDidLoad'中設置表視圖的'.rowHeight = UITableViewAutomaticDimension'。另外,爲'.estimatedRowHeight'設置一個實際值可以提高滾動性能 - 再次,只需將其設置在'viewDidLoad'中即可。 – DonMag

+0

@DonMag謝謝你的建議。 :) – PGDev

+0

此解決方案可以工作......但它可能會在「日期」標籤和單元格底部之間留下太多垂直空間。 – DonMag

相關問題