自定义 UITableViewCell 约束

时间:2021-03-15 09:04:24

标签: swift

我正在使用 UITable 创建聊天,其中包含聊天气泡的自定义单元格。像 WhatsApp 一样,我希望一些气泡在左边,一些在右边。

我正在使用 dequeueReusableCell(withIdentifier identifier: String) -> UITableViewCell?,它调用单元格的 init(style:reuseIdentifier:) 方法,因此设置我的单元格:

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        cellBackground = UIView()
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        setupConstraints()
    }

    func setupConstraints() {
        NSLayoutConstraint.activate([
            cellBackground.topAnchor.constraint(equalTo: contentView.topAnchor),
            cellBackground.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
            cellBackground.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
            cellBackground.widthAnchor.constraint(equalTo: contentView.widthAnchor, multiplier: 0.5)
        ])
    }

但这并不令人满意。由于存在leadingAnchor 约束,单元格总是在左边——当单元格在右边时,它需要是一个trailingAnchor 约束。

如果我为单元格使用设置函数,应该在那里调用 setupConstraints,还是 init 设置它当时知道的约束?或者,这些约束是否都应该在 layoutSubviews() 中设置?

1 个答案:

答案 0 :(得分:0)

添加 2 个实例变量作为对单元格自定义类内的前导和尾随约束的引用

var leadCon,traCon:NSLayoutConstraint!

然后在init里面也出来了activate

 leadCon = cellBackground.leadingAnchor.constraint(equalTo: contentView.leadingAnchor)
 leadCon.isActive = true

traCon = cellBackground.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
traCon.isActive = true

根据需要添加功能

func toLeft(_ value:Bool) {
   if value {
     leadCon.isActive = true
     traCon.isActive = false
   }
   else { 
     leadCon.isActive = false
     traCon.isActive = true
   }
}

并在 dequeue 中的 cellForRowAt 行之后调用它