IOS: dynamic height of UILabel using sizeWithFont: constrainedToSize: lineBreakMode: not working

I am trying to give a dynamic UILabel height UILabel that my layout of the other labels looks correct in both landscape and portrait.

In the portrait, my text is wrapped in the second line, in the landscape - no. Thus, when using sizeWithFont:constrainedToSize:lineBreakMode: I get the same height when rotating in both directions when I assumed that it would be a larger number if the text was 2 lines.

How can I get the height of my UILabel when it has two lines of text or more (portrait) and get a new height, which is one line when in the landscape?

I think I don’t understand how to make dynamic height work ...

 UILabel *itemTitle = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, top, screen.size.width - 20, 200.0f)]; itemTitle.text = self.newsAsset.title; itemTitle.adjustsFontSizeToFitWidth = NO; itemTitle.autoresizingMask = UIViewAutoresizingFlexibleWidth; itemTitle.font = [UIFont boldSystemFontOfSize:18.0]; itemTitle.textColor = [UIColor blackColor]; itemTitle.shadowColor = [UIColor whiteColor]; itemTitle.shadowOffset = CGSizeMake(0, 1); itemTitle.backgroundColor = [UIColor blueColor]; itemTitle.lineBreakMode = UILineBreakModeWordWrap; itemTitle.numberOfLines = 0; [itemTitle sizeToFit]; // Set the height CGSize maximumLabelSize = CGSizeMake(300,9999); CGSize titleSize = [itemTitle.text sizeWithFont:itemTitle.font constrainedToSize:maximumLabelSize lineBreakMode:itemTitle.lineBreakMode]; NSLog(@"Height: %.f Width: %.f", titleSize.height, titleSize.width); //Adjust the label the the new height CGRect newFrame = itemTitle.frame; newFrame.size.height = titleSize.height; itemTitle.frame = newFrame; // Add them! [headerView addSubview:itemTitle]; [itemTitle release]; top += titleSize.height; 
+4
source share
2 answers

change the line where you set maximumLabelSize to

 CGSize maximumLabelSize = CGSizeMake(headerView.bounds.size.width, CGFLOAT_MAX); 
+3
source

In your code, as of right now, in any orientation you will get the same width and height, since you always go 300 widths to the sizeWithFont method. If you make it dynamic, perhaps the result of sizeWithFont will also change dynamically.

0
source

Source: https://habr.com/ru/post/1346635/


All Articles