控件的位置和大小有三种确定方式:frame autoresizingMask autolayout
- frame设置位置和大小:是绝对位置,大小不会随父视频变化而变化
- autoresizing(autoresizingMask):默认是不开启。一般和frame共同使用,可以和父视图成比例变化或是固定的父视图的间
- autolayout:功能大,可以于父视图或兄弟试图建立约束关系。若要使用autolayout需设置translatesAutoresizingMaskIntoConstraints属性为NO
autolayout
-
intrinsicContentSize 在autolayout中的应用:
当我们的控件大小由自身内容决定,或是固定大小,我们可以通过设置intrinsicContentSize来让控件自己决定大小,当我们使用控件的时候,可以只设置位置约束即可,也可以自己设置大小约束。
-
setContentHuggingPriority 在autolayout中的应用:
当我们通过intrinsicContentSize让控件自己设置大小 或 设置大小约束为某一范围时范围(NSLayoutRelationGreaterThanOrEqual),控件是可以拉伸的。通过setContentHuggingPriority设置某一方向的抗拉伸约束,可以使其比其他抗拉伸的控件更容易或难拉伸。
-
setContentCompressionResistancePriority 在autolayout中的应用:
当我们通过intrinsicContentSize让控件自己设置大小 或 设置大小约束为某一范围时范围(NSLayoutRelationLessThanOrEqual),控件是可以压缩的。通过setContentCompressionResistancePriority设置某一方向的抗压缩约束,可以使其比其他抗压缩的控件更容易或难压缩。
-
preferredMaxLayoutWidth 在autolayout中的应用:
当label文字需要换行时,设置preferredMaxLayoutWidth=100,可以使intrinsicContentSize计算出换行后的大小尺寸。
-
为控件添加约束:
_label = [[UILabel alloc] init]; _label.translatesAutoresizingMaskIntoConstraints = NO; _label.backgroundColor = [UIColor redColor]; _label.text = @"是我的就是我的"; [self.view addSubview:_label]; NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:_label attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:20]; NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:_label attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:40]; [self.view addConstraints:@[left,top]];
网友评论