iOS: 在代码中使用Autolayout (2) – intrinsicContentSize和Content Hugging Priority

http://www.mgenware.com/blog/?p=491

继续用代码来写Autolayout,先写一个辅助方法来快速设置UIView的边距限制:
//设置Autolayout中的边距辅助方法
- (void)setEdge:(UIView*)superview view:(UIView*)view attr:(NSLayoutAttribute)attr constant:(CGFloat)constant
{
    [superview addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:attr relatedBy:NSLayoutRelationEqual toItem:superview attribute:attr multiplier:1.0 constant:constant]];
}

//接下来,创建一个UIView,利用上面的辅助方法快速设置其在父控件的左,上,右边距为20单位。如下代码:
//view1
UIView *view1 = [UIView new];
view1.backgroundColor = [UIColor yellowColor];
//不允许AutoresizingMask转换成Autolayout
view1.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:view1];
//设置左,上,右边距为20.
[self setEdge:self.view view:view1 attr:NSLayoutAttributeLeft constant:20];
[self setEdge:self.view view:view1 attr:NSLayoutAttributeTop constant:20];
[self setEdge:self.view view:view1 attr:NSLayoutAttributeRight constant:-20];


你可能感兴趣的:(ios)