Pet*_*her 5 cocoa-touch ios autolayout swift
我发现了systemLayoutSizeFittingSize:我预期的方法的不同行为.
这是一个快速Playground的代码,它演示了行为,但它在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()
Run Code Online (Sandbox Code Playgroud)
我原以为是,layoutSize并且intrinsicSize是一样的.
但是,在这种情况下,layoutSize是(w 173, h 20)和intrinsicSize是(w 40, h 104)
我希望两者都是,intrinsicSize但它似乎systemLayoutSizeFittingSize:忽略了preferredMaxLayoutWidth
有人能够向我解释一下吗?
编辑:还
label.setNeedsLayout()
label.layoutIfNeeded()
let layoutSize = label.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
let intrinsicSize = label.intrinsicContentSize()
Run Code Online (Sandbox Code Playgroud)
不会改变结果
内在大小是内容视图的计算,您在示例中得到了预期的结果。另一方面,layoutSize 取决于视图的约束,因为您没有定义任何系统使用不使用固有大小的默认值。但是,如果您向标签添加一些约束,即在视图中垂直和水平居中,那么系统将使用内在内容大小来最终确定布局,并且两个大小将相同。
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));
Run Code Online (Sandbox Code Playgroud)
对于这种情况,输出是:
2015-01-29 01:00:46.265 test[31327:911898]
layout: {38.5, 130.5}
intrinsicSize:{38.5, 130.5}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4324 次 |
| 最近记录: |