我正在以编程方式创建带有自定义单元格的表格视图。我想在自定义单元格中使用带有已安排子视图的堆栈视图。但是,我所有的努力都失败了。首先可以这样做吗?
第二,我将代码放在以下位置:
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: "cellId")
我正在使用以下代码创建堆栈视图:
let thestack: UIStackView = {
let sv = UIStackView()
sv.distribution = .fillEqually
sv.axis = .vertical
sv.spacing = 8
return sv
}()
但是我不能在其中添加排列后的子视图,除了在我添加子视图(thestack)并列出所有约束之后,我的数据都没有显示在自定义单元格中。任何帮助将不胜感激。
答案 0 :(得分:1)
是的,有可能。如下所示:
class CustomTableViewCell: UITableViewCell {
let stackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.spacing = 10
stackView.distribution = .fillEqually
return stackView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
addSubview(stackView)
stackView.leftAnchor.constraint(equalTo: leftAnchor, constant: 10).isActive = true
stackView.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true
stackView.rightAnchor.constraint(equalTo: rightAnchor, constant: -10).isActive = true
stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -10).isActive = true
let redView = UIView()
redView.backgroundColor = .red
let yellowView = UIView()
yellowView.backgroundColor = .yellow
let blackView = UIView()
blackView.backgroundColor = .black
stackView.addArrangedSubview(redView)
stackView.addArrangedSubview(yellowView)
stackView.addArrangedSubview(blackView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
输出: