Reputation: 1759
I would like to accomplish what is seen in the image below in Interface Builder. Basically two labels - one multi-line and one note - inside a view and the view centered horizontally on the page. So to be clear, I cannot put a width constraint on the view or the centering will not work correctly.
I can get the label with the actual hours to multi-line when it is not in a view but when I place it in a view and set up the Top, Left and Right constraints - the label reverts back to a single line.
below are the constraints and attributes for the label in the view and a picture of what IB does when i update the frames. Any suggestions would be greatly appreciated.
There are the constraints for the label with just the work Hours in it:
This is what it looks like after I update the frames
Upvotes: 1
Views: 1702
Reputation: 104082
Either your multi-line label, or the outer view needs to have its width constrained in some way, otherwise the label will expand its width to whatever it needs to accommodate the text on one line. If that line is long enough, the text will run off the edge of the view, which is what appears to be happening in your last image.
After Edit:
To make the view centered when the list of hours is short, but still allow the view to be wide when the hours list is long, give the outer view a <= width constraint to the superview. In IB select your view then the superview, and choose "equal widths", and then edit that to be <=. The default hugging priority will keep that outer view small if the list is short, but if the list grows long enough to go to multiple lines, you still have the width constraint to force it to do so.
I found that adding this <= constraint in IB didn't work correctly on rotation. If the label was multi-line in portrait, and thus the labelsView (the view containing the 2 labels) was expanded to the full width of the screen, on rotation labelsView maintained that same width, instead of adjusting to the new size. I think this is a bug in the system. Fortunately, adding the same constraint in code, worked fine.
override func viewDidLoad() {
super.viewDidLoad()
view.addConstraint(NSLayoutConstraint(item: labelsView, attribute: .Width, relatedBy: .LessThanOrEqual, toItem: self.view, attribute: .Width, multiplier: 1, constant: 0))
}
Upvotes: 1