首页 > 解决方案 > 以编程方式自定义单元格和堆栈视图

问题描述

我正在以编程方式创建一个带有自定义单元格的表格视图。我想在自定义单元格中使用带有排列子视图的堆栈视图。然而,我所有的努力都失败了。首先可以做到这一点吗?

其次,我将代码放在:

 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
    }()

但是我不能将排列好的子视图添加到此之外,在我 addsubview(thestack) 并列出所有约束之后 - 我的数据都没有显示在自定义单元格中。任何帮助,将不胜感激。

标签: swiftuitableviewcellstackview

解决方案


对的,这是可能的。如下所示:

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")
}
}

推荐阅读