【问题标题】:Custom cell and stack-view programmatically以编程方式自定义单元格和堆栈视图
【发布时间】:2018-12-13 16:49:40
【问题描述】:

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

其次,我将代码放在:

 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) 并列出了所有约束 - 我的数据均未显示在自定义单元格中。任何帮助将不胜感激。

【问题讨论】:

  • 向我们展示您列出所有约束的代码并尝试添加排列的子视图。

标签: swift uitableview cell stackview


【解决方案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")
}
}

【讨论】:

  • 如果它工作正常,请点赞帮助他人的答案。
  • 点击我的答案上的向上箭头并将其标记为工作。
  • 在常规 UIView 上使用堆栈视图的关键是您必须使用 addArrangedSubview 而不是普通的 addSubview。
猜你喜欢
  • 1970-01-01
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-30
  • 2017-06-18
  • 1970-01-01
相关资源
最近更新 更多