【发布时间】:2016-12-08 11:33:03
【问题描述】:
我有一个表格,其中包含自定义单元格。这些单元格包含一个图像视图和两个标签。我有约束来定位典型单元的所有内容。
每个单元格代表一个文件或一个文件夹。我设置的布局用于文件视图(两个标签是名称和详细信息)。当我创建自定义单元格时,我将图标更改为文件夹,详细信息标签变为隐藏。然后我将名称标签居中以使其更漂亮。
我的问题来自重复使用单元格。我似乎无法从名称标签的中心恢复。我尝试了几种不同的方法来添加这个约束,并且似乎总是能够让约束第一次起作用,但是一旦一个单元被重用,我就会遇到问题。
我注意到的一件事是我只有在单元格尝试删除新的中心约束时才会遇到问题(单元格从文件夹单元格转到文件单元格)
目录单元类
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
}
}
【问题讨论】:
标签: ios swift uitableview constraints