Reputation: 135
I have a function that creates an array UIStackViews
with UIButtons
inside of it:
func generateStackViews() -> [UIStackView] {
var stackViewArray = [UIStackView]()
let finalButtonArray = generateButtons()
for buttons in finalButtonArray{
stackViewArray.append(createStackView(subViews: buttons))
}
return stackViewArray
}
I then add that array to a tableViewCell
:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "First")!
cell.contentView.addSubview(generateStackViews()[indexPath.row])
return cell
}
Everything works fine, but when I try to add constraints to pin the stackViews
to the cells, I get this error:
failure in -[UITableViewCell _layoutEngine_didAddLayoutConstraint:roundingAdjustment:mutuallyExclusiveConstraints:]
I tried adding the constraints in the function that creates the stackViews
and in the cellForRowAt
function, tried to pin it to the contentView
, cell and tableView
, but neither worked and I got the same error message.
Where is my logic failing?
Upvotes: 1
Views: 1050
Reputation: 3677
call this method to addContraints Programatically.
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)
}
and call the above method like this.
self.addSubviewWithConstraint(to: cell.contenetView, and: stackView, top: 0, bottom: 0, leading: 0, trailing: 0)
Upvotes: 3