我有一個表內有自定義單元格。這些單元格包含一個圖像視圖和兩個標籤。我有限制爲一個典型的細胞定位一切。如何調整自定義單元格中的標籤約束?
每個單元表示一個文件或文件夾。我設置的佈局是用於文件視圖(兩個標籤是名稱和詳細信息)。當我創建自定義單元格時,我將圖標更改爲文件夾,並且細節標籤變爲隱藏。然後,我將名稱標籤居中以使其更漂亮。
我的問題來自單元格的重用。我似乎無法恢復名稱標籤的中心位置。我嘗試了幾種不同的方法來添加這個約束,並且似乎總能第一次使用約束,但是一旦單元被重用,我會遇到問題。細胞被重新
細胞的
首先創作是我只有當一個小區試圖刪除新中心的約束問題(單元格從文件夾單元格到文件單元格)
目錄單元格類別
class DirectoryCell: UITableViewCell {
@IBOutlet weak var directoryTypeImage: UIImageView!
@IBOutlet weak var directoryNameLabel: UILabel!
@IBOutlet weak var directoryDetailsLabel: UILabel!
var directoryItem: DirectoryItem! {
didSet {
self.updateUI()
}
}
func updateUI() {
let centerConstraint = NSLayoutConstraint(item: directoryNameLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0.0)
let topConstraint = NSLayoutConstraint(item: directoryNameLabel, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 7.0)
directoryNameLabel.text = directoryItem.name
directoryTypeImage.image = directoryItem.typeIcon
if (directoryItem.type == DirectoryItem.types.FOLDER) {
self.removeConstraint(topConstraint)
self.addConstraint(centerConstraint)
directoryDetailsLabel.isHidden = true
} else {
self.removeConstraint(centerConstraint)
self.addConstraint(topConstraint)
directoryDetailsLabel.text = directoryItem.details
directoryDetailsLabel.isHidden = false
}
}
}
我只是申請/刪除約束錯誤或可能應用/刪除它們在不正確的地方?
當我瀏覽調試器並查看self.constraints表達式時,我沒有受到任何限制。我在哪裏誤解我的自定義單元的約束?
TL; DR
似乎無法刪除定心約束,當一個自定義單元格被重用
編輯/解決方案
對於遇到這個問題,今後的任何人申請頂部約束,丹的回答完全正確。我需要爲每個我想應用的約束創建一個屬性。然後我刪除所有的約束,並只應用我想要的。
加入DirectoryCell類
var topConstraint: NSLayoutConstraint {
get {
return NSLayoutConstraint(item: self.directoryNameLabel, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 7.0)
}
}
var centerConstraint: NSLayoutConstraint {
get {
return NSLayoutConstraint(item: self.directoryNameLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0.0)
}
}
新updateUI()
func updateUI() {
directoryNameLabel.text = directoryItem.name
directoryTypeImage.image = directoryItem.typeIcon
if (directoryItem.type == DirectoryItem.types.FOLDER) {
self.removeConstraints(self.constraints) // Remove all constraints
self.addConstraint(centerConstraint) // Add constraint I want for this "cell type"
directoryDetailsLabel.isHidden = true
} else {
self.removeConstraints(self.constraints)
self.addConstraint(topConstraint)
directoryDetailsLabel.text = directoryItem.details
directoryDetailsLabel.isHidden = false
}
}
啊,當然。我會刺傷它的。我會在完成後報告 – sargturner
謝謝@dan我做了你的建議,你完全正確。特別感謝迅速答覆! – sargturner