3

I am creating a tableview with a custom cell programmatically. I would like to utilise a stack view with arranged subviews within the custom cell. However, all my efforts have failed. Firstly is it possible to do this?

Secondly I am placing the code after:

 override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: "cellId") 

I am using this code to create the stack view:

   let thestack: UIStackView = {
        let sv = UIStackView()
        sv.distribution = .fillEqually
        sv.axis = .vertical
        sv.spacing = 8
         return sv
    }()

But I can't add the arranged subviews to this in addition to which after I addsubview(thestack) and list all the constraints - none of my data shows in the custom cell. Any help would be appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user3194306
  • 81
  • 1
  • 7

1 Answers1

8

Yes, it is possible. Follow like below:

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")
}
}
elp
  • 8,021
  • 7
  • 61
  • 120
nitin.agam
  • 1,949
  • 1
  • 17
  • 24