I have a view inside a scrollview:
Now I want to add the child views to that view programmatically. Thats my code to do that:
Child view (works)
//Adds header to the view again because it was removed in the clear() method //Header is just a label lv.addSubview(header) header.leadingAnchor.constraint(equalTo: header.superview!.leadingAnchor).isActive = true header.topAnchor.constraint(equalTo: header.superview!.topAnchor, constant: 2).isActive = true header.widthAnchor.constraint(equalTo: header.superview!.widthAnchor).isActive = true header.heightAnchor.constraint(equalToConstant: MainTabViewController.fontSize*3).isActive = true //Just a constant
Now I execute this code repeatedly:
private func makeTextLabel(text: NSAttributedString, bgColor: UIColor?, maxWidth: CGFloat?) -> UILabel {
//Creates label
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
lv.addSubview(label)
//Adjustments
if(bgColor != nil) {
label.backgroundColor = bgColor
}
label.textColor = UIColor.black
label.attributedText = text
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
let width = maxWidth ?? lv.frame.size.width-8
label.widthAnchor.constraint(equalToConstant: width).isActive = true
label.heightAnchor.constraint(equalToConstant: heightForLabel(attributedText: label.attributedText, width: width)).isActive = true
label.leadingAnchor.constraint(equalTo: lv.leadingAnchor, constant: 4).isActive = true
let previousView = lv.subviews[lv.subviews.count-1]
label.topAnchor.constraint(equalTo: previousView.bottomAnchor, constant: 10).isActive = true
return label
}
All the labels are added, but the constraints dont work at all. Here is what is looks like (when I execute the method above 2 times):
EDIT: The main problem is solved. I am using a StackView now.(https://stackoverflow.com/a/59828434/6257435)
I now want my labels to have an offset to the edges, so I use those lines:
label.leadingAnchor.constraint(equalTo: lessonStackView.leadingAnchor, constant: offset).isActive = true
label.trailingAnchor.constraint(equalTo: lessonStackView.trailingAnchor, constant: -offset).isActive = true
But as the StackView seems to set x-constraints itself, I get this warning:
Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. ( "UILabel:0x7f9c16c22c30'Falls dir die App gef\U00e4llt...' (active, names: '|':JavaProf.MultipleContentsView:0x7f9c19024a60 )>", "", "" )
Will attempt to recover by breaking constraint
How can I solve that?