Creating a dynamically sizing UILabel in the Xcode interface builder

两盒软妹~` 提交于 2019-12-11 21:36:01

问题


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:

  1. center the label horizontally in the view
  2. set a width constraint of <= 500
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!