问题
I want to be able to create a UILabel that will adjust it's size in a more complex way than normal AutoLayout. I've looked over the internet for an answer to this, but to no avail.
Here's what I want it to do.
Say you're viewing it on an iPhone. I want it to be 16 points away from either edge centered in the middle. (Height does not matter in any of this)
However, when the screen gets wider, I want the UILabel to stretch so that it's 16 points away form each edge UNTIL it reaches, say, 500 width. Once it reaches 500 width, I don't want it to get any wider. This is where the 16 points on either side increases, still keeping the label in the center.
Now you're viewing it on an iPad landscape. The UILabel is exactly 500 points wide and in the center.
If possible, I would like to be able to accomplish this using AutoLayout, and not code, but if code is a must, I can deal with that.
Thank you for your consideration. All help is appreciated.
回答1:
You can do this with 3 constraints:
- center the label horizontally in the view
- set a width constraint of <= 500
- set a leading space constraint of 16. Give this a priority of < 1000.
When the view is wide (like on an iPad), the label will stretch to its full width of 500
. Auto Layout will keep the label centered, and it will try its best to satisfy the 3rd constraint by keeping the the leading space as close to 16
as possible. It chooses to break this constraint because the priority is less than 1000
.
When the view is narrow (like on an iPhone), the label will have a leading space of 16
(and trailing space of 16
because the label is centered). The width will be whatever is left, because that satisfies the width <= 500
constraint.
来源:https://stackoverflow.com/questions/50557236/creating-a-dynamically-sizing-uilabel-in-the-xcode-interface-builder