【问题标题】:constraints are not behaving consistently when set conditionally有条件设置时,约束的行为不一致
【发布时间】: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


【解决方案1】:

在返回单元格之前尝试添加以下行:

cell.setNeedsLayout()
cell.layoutIfNeeded()

我认为某些单元格的布局更改在滚动时会被丢弃,因为这些单元格被重复使用。

【讨论】:

  • 感谢您回来。在进行了几次实验后,我决定这种方法行不通,所以我放弃了这部分设计
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-23
  • 2010-10-26
  • 2021-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多