iOS Autolayout: Issue with UILabels in a resizing parent view

后端 未结 3 2008
无人共我
无人共我 2020-12-04 10:43

I\'ve got a view that contains only a UILabel. This label contains multiline text. The parent has a variable width that can be resized with a pan gesture. My problem is t

3条回答
  •  广开言路
    2020-12-04 10:51

    I've fixed this issue after raising a bug with Apple. The issue that multiline text requires a two-pass approach to layout and it all relies on the property preferredMaxLayoutWidth

    Here is the relevant code that needs to be added to a view controller that contains a multiline label:

    - (void)viewWillLayoutSubviews
    {
        // Clear the preferred max layout width in case the text of the label is a single line taking less width than what would be taken from the constraints of the left and right edges to the label's superview
        [self.label setPreferredMaxLayoutWidth:0.];
    }
    
    - (void)viewDidLayoutSubviews
    {
        // Now that you know what the constraints gave you for the label's width, use that for the preferredMaxLayoutWidth—so you get the correct height for the layout
        [self.label setPreferredMaxLayoutWidth:[self.label bounds].size.width];
    
        // And then layout again with the label's correct height.
        [self.view layoutSubviews];
    }
    

提交回复
热议问题