【问题标题】:How to add constraints to UIStackView inside of a UITableViewCell swift programmatically?如何以编程方式快速向 UITableViewCell 内的 UIStackView 添加约束?
【发布时间】:2017-01-20 22:28:12
【问题描述】:

我有一个函数可以创建一个数组UIStackViews,其中包含UIButtons

func generateStackViews() -> [UIStackView] {
    var stackViewArray = [UIStackView]()
    let finalButtonArray = generateButtons()
    for buttons in finalButtonArray{
        stackViewArray.append(createStackView(subViews: buttons))
    }
    return stackViewArray
}

然后我将该数组添加到 tableViewCell:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "First")!
    cell.contentView.addSubview(generateStackViews()[indexPath.row])
    return cell
}

一切正常,但是当我尝试添加约束以将 stackViews 固定到单元格时,我收到此错误:

失败 -[UITableViewCell _layoutEngine_didAddLayoutConstraint:roundingAdjustment:mutuallyExclusiveConstraints:]

我尝试在创建stackViews 的函数和cellForRowAt 函数中添加约束,尝试将其固定到contentView、单元格和tableView,但都不起作用,我得到了同样的错误消息。

我的逻辑哪里出错了?

【问题讨论】:

    标签: ios swift uitableview ios-autolayout uistackview


    【解决方案1】:

    以编程方式调用此方法以添加约束。

    func addSubviewWithConstraint(to parentView: UIView, and childView: UIView, top:CGFloat, bottom:CGFloat, leading:CGFloat, trailing:CGFloat) {
        parentView.addSubview(childView)
        //Below line tells the view to not use AutoResizing
        childView.translatesAutoresizingMaskIntoConstraints = false
        // set top constraint
        let topConstraint = NSLayoutConstraint(item: childView, attribute: .top, relatedBy: .equal, toItem: parentView, attribute: .top, multiplier: 1, constant: top)
        // set Bottom constraint
        let bottomConstraint = NSLayoutConstraint(item: childView, attribute: .bottom, relatedBy: .equal, toItem: parentView, attribute: .bottom, multiplier: 1, constant: bottom)
        // set leading constraint
        let leadingConstraint = NSLayoutConstraint(item: childView, attribute: .leading, relatedBy: .equal, toItem: parentView, attribute: .leading, multiplier: 1, constant: leading)
        // set Bottom constraint
        let trailingConstraint = NSLayoutConstraint(item: childView, attribute: .trailing, relatedBy: .equal, toItem: parentView, attribute: .trailing, multiplier: 1, constant: trailing)
        //Add all constraints to parentView
        parentView.addConstraint(topConstraint)
        parentView.addConstraint(bottomConstraint)
        parentView.addConstraint(leadingConstraint)
        parentView.addConstraint(trailingConstraint)
    }
    

    然后像这样调用上面的方法。

    self.addSubviewWithConstraint(to: cell.contenetView, and: stackView, top: 0, bottom: 0, leading: 0, trailing: 0)
    

    【讨论】:

    • 非常感谢,这很有帮助。我是初学者,所以如果你能解释这背后的逻辑,将不胜感激
    猜你喜欢
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多