简体   繁体   中英

Setting UILabel to width of screen and height to fit contained text

I am trying to layout a detail view of my application. The view has a title, some information, and a description. I would like to set the width of my title label and the description label to be the width of the screen and the height of those labels to accommodate the contents of the labels. I also want the entire view to scroll if the height of the content is too large to fit on the screen.

I currently have a xib with the labels inside a view, with autolayout constraints to position the objects and set the width of the title label and description label to the size of the containing view. That view is inside a UIScrollView but does not have any constraints on it. I set the labels to accommodate multiple lines in the attributes inspector. I set the width of the view with the content and the scroll view content size and frame in my viewDidLoad method.

Currently I cannot get the labels to be the width of the screen and the height to automatically accommodate the text. Am I on the right path or do I need to try a different method?

To accommodate the height of the text inside, use 0 as the number of lines in the UILabel. That will automatically make them grow according to the text inside. You will also need to add a constraint from the last element inside your UIScrollView to the bottom of the scroll view, to avoid ambiguous content size.

To get the labels to be the width of the screen, it should be a straightforward constraint from the label to it's container. However, if the label is within the scroll view, you might have to constrain the label to have the same width as the scroll view, because constraining the label to the leading and trailing edges of the scroll view will constrain it to the scrollview's content view, which grows according to its contained views.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM