我有一个函数可以在其中创建一个带有schoolB_courses
的数组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
}
固定到单元格时,我收到此错误:
失败 - [UITableViewCell _layoutEngine_didAddLayoutConstraint:roundingAdjustment:mutualExclusiveConstraints:]
我尝试在创建stackViews
和stackViews
函数的函数中添加约束,尝试将其固定到cellForRowAt
,单元格和contentView
,但是没有工作,我得到了同样的错误信息。
我的逻辑在哪里失败?
答案 0 :(得分:3)
以编程方式将此方法称为addContraints。
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)