以编程方式在stackView中布置子视图

时间:2019-08-11 19:03:52

标签: ios swift uitableview uistackview

我希望UITableCell包含可变数量的按钮,例如“是”和“否”按钮,或“红色”,“绿色”和“蓝色”按钮。我尝试了各种方法,但决定在单元格中使用垂直的stackView并以编程方式添加包含按钮的视图(请在此处建议一种更好的方法)。

我遇到的问题是我不知道自动布局在做什么。通常,在接口构建器中将视图添加到stackView时,只需要一个height值,然后它们就可以很好地堆叠。但是,以下代码似乎为它们提供了零宽度,如果我设置了宽度,则视图全部位于彼此之上。注意,这不包括我上面提到的使响应变得更容易的按钮。我刚刚添加了两个视图。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "formQuestion") as! FormQuestionTableViewCell
    let view = UIView(frame: .zero)
    view.backgroundColor = UIColor.red
    view.translatesAutoresizingMaskIntoConstraints = false
    cell.questionOptions.addSubview(view)
    NSLayoutConstraint.activate([
        view.heightAnchor.constraint(equalToConstant: 8)
        // , view.widthAnchor.constraint(equalToConstant: 16)
    ])
    let view2 = UIView(frame: .zero)
    view2.backgroundColor = UIColor.blue
    view2.translatesAutoresizingMaskIntoConstraints = false
    cell.questionOptions.addSubview(view2)
    NSLayoutConstraint.activate([
        view2.heightAnchor.constraint(equalToConstant: 32)
        // , view2.widthAnchor.constraint(equalToConstant: 64)
    ])
    return cell
}

为了完整起见,FormQuestionTableViewCell看起来像这样...

class FormQuestionTableViewCell: UITableViewCell {

    @IBOutlet weak var descriptionContainer: UIView!
    @IBOutlet weak var controlContainer: UIView!
    @IBOutlet weak var descriptionLabel: UILabel!
    @IBOutlet weak var questionOptions: UIStackView!

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }
}

启用宽度限制后,它看起来像这样(尽管我认为这不是必须的)...

AutoLayout problem illustration

非常感谢您能给我的帮助!

2 个答案:

答案 0 :(得分:1)

这是错误的:

cell.questionOptions.addSubview(view)

UIStackView添加子视图时,应使用:

.addArrangedSubview()

参考:

https://developer.apple.com/documentation/uikit/uistackview/1616227-addarrangedsubview

答案 1 :(得分:1)

你在说

cell.questionOptions.addSubview(view)

错了。 questionOptions是堆栈视图。如果您希望它负责布局view,则必须说

cell.questionOptions.addArrangedSubview(view)