Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

systemLayoutSizeFittingSize: on UILabel not behaving like expected

I found a different behavior of the systemLayoutSizeFittingSize: method then i expected.

Here is an code snipped for a swift Playground which demonstrates the behavior but its the same 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 have expected that layoutSize and intrinsicSize are the same.

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

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

Is somebody able to explain it to me?

Edit: Also

label.setNeedsLayout()
label.layoutIfNeeded() 

let layoutSize = label.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)

let intrinsicSize = label.intrinsicContentSize()

doesn't change the results

like image 464
Peter Schumacher Avatar asked Oct 20 '22 02:10

Peter Schumacher


1 Answers

The intrinsic size is the calculation of the content's view, and you get in your example the expected results. On the other hand layoutSize depends of the view's constrains, since you didn't define any the system use default ones that don't use the intrinsic size. But if you use add a couple of constraints to the label, i.e. center in the view vertically and horizontally then the system will use the intrinsic content size to finally determine the layout and both sizes would be the same.

Code example 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));

For 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}
like image 133
Pablo Carrillo Alvarez Avatar answered Oct 26 '22 22:10

Pablo Carrillo Alvarez