SystemLayoutSizeFittingSize: on UILabel not working as expected

I found another behavior of the systemLayoutSizeFittingSize: method, after which I expected.

Here is a code snippet for a fast playground that demonstrates behavior, but the same thing in Objective-C:

 import UIKit import Foundation var label = UILabel() label.text = "This is a Test Label Text" label.numberOfLines = 0 label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) label.preferredMaxLayoutWidth = 40 let layoutSize = label.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) let intrinsicSize = label.intrinsicContentSize() 

I would expect layoutSize and intrinsicSize match.

But in this case, layoutSize is (w 173, h 20) and intrinsicSize is (w 40, h 104)

I would expect both to be intrinsicSize , but it seems that systemLayoutSizeFittingSize: ignores preferredMaxLayoutWidth

Can anyone explain this to me?

Edit: Also

 label.setNeedsLayout() label.layoutIfNeeded() let layoutSize = label.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) let intrinsicSize = label.intrinsicContentSize() 

does not change the results

+5
source share
1 answer

The internal size is the calculation of the presentation of the content, and you will get the expected results in your example. On the other hand, layoutSize depends on the limitations of the view, since you have not indicated that the system uses by default those that do not use internal size. But if you use to add a few restrictions to the label, that is, in the center in the vertical and horizontal views, the system will use its own content size to finally determine the layout, and both sizes will be the same.

Example code in objective-c:

 //This code assume you have a UILabel as IBOutlet named testLabel with two constrains // to center the view, then in "viewDidLoad:" self.testLabel.text =@ "This is a Test Label Text"; self.testLabel.font = [UIFont preferredFontForTextStyle:(UIFontTextStyleBody)]; self.testLabel.numberOfLines = 0; self.testLabel.preferredMaxLayoutWidth = 40; CGSize layoutSize1 = [_testLabel systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; CGSize intrinsicSize1 = [_testLabel intrinsicContentSize]; NSLog(@"\nlayout:%@\nintrinsicSize:%@",NSStringFromCGSize(layoutSize1),NSStringFromCGSize(intrinsicSize1)); 

In this case, the output is:

 2015-01-29 01:00:46.265 test[31327:911898] layout: {38.5, 130.5} intrinsicSize:{38.5, 130.5} 
+3
source

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


All Articles