Update your preferred MaxLayoutWidth for multi-line UILabel with unknown size (Auto Layout)

I have my own view class that inherits from UIView . This class has UILabel as its subclause. In the init function of this custom view class, I configured everything you need:

 //h-file #import <UIKit/UIKit.h> @interface MyCustomView : UIView @property (strong, nonatomic) UILabel *myLabel; @end //m-file @implementation MyCustomView @synthesize myLabel = _myLabel; - (id)init { self = [super init]; if (self) { _myLabel = [UILabel new]; if(_textView){ _myLabel.highlightedTextColor = [UIColor whiteColor]; _myLabel.translatesAutoresizingMaskIntoConstraints = NO; _myLabel.lineBreakMode = NSLineBreakByWordWrapping; _myLabel.numberOfLines = 0; _myLabel.backgroundColor = [UIColor clearColor]; [self addSubview:_myLabel]; } } return self; } @end 

I also created many constraints to control the padding inside my user view - in addition, there are restrictions on the layout of several MyCustomView tools for both the vertical and horizontal axis.

To get multi-line label output, I have to set preferredMaxLayoutWidth -property UILabel myLabel . Width depends on free space. In http://www.objc.io/issue-3/advanced-auto-layout-toolbox.html I read that I can let the auto-layout first calculate the width and set it as preferredMaxLayoutWidth after the MyCustomView -instance frame (the shortcut is currently set inside one layer).

If I put the following function in MyCustomView , the label still has one line of text:

 - (void)layoutSubviews { [super layoutSubviews]; float width = _myLabel.frame.size.width; _myLabel.preferredMaxLayoutWidth = width; [super layoutSubviews]; } 

If I set preferredMaxLayoutWidth to an explicit value inside the init function, the label is multi-line.

Does anyone know what I'm doing wrong here?

Thanks in advance!

+4
source share
1 answer

Without seeing all the restrictions that you have configured for your custom view and the supervisor that contains it, it is very difficult to determine the problem, I suggest you print all the view frames of the entire hierarchy of views, starting from the controller view in the ViewDidLayoutSubviews view and determine if the label has her supervisors are the right frame set.

I had similar problems with dynamic label size and scrolling, so I created a prototype here, it may also be useful for you: https://github.com/briandotnet/AutoLayoutScrollViewExperiment

0
source

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


All Articles