【发布时间】:2017-03-01 22:34:36
【问题描述】:
当我有条件地为自定义表格单元格设置约束时遇到问题。例如,我在自定义表格单元格中有两个 UIImageView。它们相互约束,但偏移量取决于单元格内容。
当我设置 UITableView 时,一切看起来都很好,但是当我滚动单元格时,约束停止工作并且图像正在跳跃。我的代码如下所示:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! MyTableViewCell
if myArray[indexPath.row] == "Farmyard" {
cell.image1.image = UIImage(named: "Barn")
cell.image2.image = UIImage(named: "Tractor")
// offset +10
cell.image2.centerXAnchor.constraint(equalTo: cell.image1.centerXAnchor, constant: 10).isActive = true
} else if myArray[indexPath.row] == "Factory" {
cell.image1.image = UIImage(named: "Warehouse")
cell.image2.image = UIImage(named: "Truck")
// offset +20
cell.image2.centerXAnchor.constraint(equalTo: cell.image1.centerXAnchor, constant: 20).isActive = true
}
return cell
}
class MyTableViewCell: UITableViewCell {
var image1: UIImageView!
var image2: UIImageView!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
image1 = UIImageView()
contentView.addSubview(image1)
image1.translatesAutoresizingMaskIntoConstraints = false
image2 = UIImageView()
contentView.addSubview(image2)
image2.translatesAutoresizingMaskIntoConstraints = false
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:)")
}
}
当我滚动浏览表视图时,条件约束似乎丢失了。当我上下滚动时,我发现越来越多的图像位置错误。有没有人也有这个问题或知道用自定义单元格设置条件约束的另一种方法?当我从 cellForRowAt 方法设置约束时,我只看到这个问题。从自定义单元格中设置的约束按预期运行。我最终想使用多个图像和标签,因此无法设置多个自定义单元格。
【问题讨论】:
-
你能分享你的整个代码吗?
标签: swift uitableview constraints