gpt4 book ai didi

ios - 如何以编程方式快速向 UITableViewCell 内的 UIStackView 添加约束?

转载 作者:搜寻专家 更新时间:2023-11-01 06:35:50 25 4
gpt4 key购买 nike

我有一个函数可以创建一个数组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 固定到单元格时,出现此错误:

failure in -[UITableViewCell _layoutEngine_didAddLayoutConstraint:roundingAdjustment:mutuallyExclusiveConstraints:]

我尝试在创建 stackViews 的函数和 cellForRowAt 函数中添加约束,试图将其固定到 contentView, cell 和 tableView,但都不起作用,我收到了相同的错误消息。

我的逻辑哪里出错了?

最佳答案

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

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)

关于ios - 如何以编程方式快速向 UITableViewCell 内的 UIStackView 添加约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41773373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com