swift - 有条件地设置时,约束的行为不一致

标签 swift uitableview constraints

当我有条件地为自定义表格单元格设置约束时遇到问题。例如,我在自定义表格单元格中有两个 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:)")
    }
}

当我滚动浏览表格 View 时,条件约束似乎丢失了。当我上下滚动时,我发现越来越多的图像位置错误。有没有人也有这个问题或知道另一种使用自定义单元格设置条件约束的方法?当我从 cellForRowAt 方法设置约束时,我只看到这个问题。从自定义单元格中设置的约束按预期运行。我最终想使用多个图像和标签,因此无法设置多个自定义单元格。

最佳答案

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

cell.setNeedsLayout()
cell.layoutIfNeeded()

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

关于swift - 有条件地设置时,约束的行为不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42543417/

相关文章:

ios - Popoverpresentation View Controller 和约束问题

ios - 何时更新 CoreData 持久容器值

ios - 将数据保存在一个类中以供另一个函数重用

iphone - 在 iPhone 邮件应用程序上重新创建蓝色 “unread dot” 的功能

ios - 向 UITableView 添加了错误的对象

ios - 如何使用 Storyboard在自定义 uitableview 中为 5 个 UILabel 系列提供约束?

ios - 使用 MBTiles 和矢量切片进行离线地理编码

ios - 为什么 NSBundle bundleIdentifier 是可选的?

ios - 如何在 Swift3 中使用 Enum 在 UITableView 中分配自定义单元格?

sql - 在 Postgresql 中,是否可以在不将约束添加到实体的情况下表达和检查约束?