设置完约束之后一定要激活约束才生效

2018/9/30 posted in  iOS
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        UILabel * messageLabel = [[UILabel alloc]init];
        messageLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview:messageLabel];
        NSArray * constrains = @[
        [messageLabel.topAnchor constraintEqualToAnchor:self.topAnchor],
        [messageLabel.leadingAnchor constraintEqualToAnchor:self.leadingAnchor],
        [messageLabel.trailingAnchor constraintEqualToAnchor:self.trailingAnchor],
        [messageLabel.bottomAnchor constraintEqualToAnchor:self.bottomAnchor]];
        
        [NSLayoutConstraint activateConstraints:constrains];
        
        
    }
    
    return self;
    
}

translatesAutoresizingMaskIntoConstraints属性要注意。

官方注释

/* By default, the autoresizing mask on a view gives rise to constraints that fully determine
the view's position. This allows the auto layout system to track the frames of views whose
layout is controlled manually (through -setFrame:, for example).
When you elect to position the view using auto layout by adding your own constraints,
you must set this property to NO. IB will do this for you.
*/

默认情况下,视图上的自动调整蒙版会产生完全确定的约束
视图的位置。这允许自动布局系统跟踪视图的框架
布局是手动控制的(例如,通过-setFrame:)。
当您选择通过添加自己的约束来使用自动布局来定位视图时,
必须将此属性设置为NO。IB会为你做这件事的。

另外还有一个比较注意的属性就是intrinsicContentSize

intrinsicContentSize,也就是控件的内置大小。比如UILabel,UIButton等控件,他们都有自己的内置大小。控件的内置大小往往是由控件本身的内容所决定的,比如一个UILabel的文字很长,那么该UILabel的内置大小自然会很长。控件的内置大小可以通过UIView的intrinsicContentSize属性来获取内置大小,也可以通过invalidateIntrinsicContentSize方法来在下次UI规划事件中重新计算intrinsicContentSize。如果直接创建一个原始的UIView对象,显然它的内置大小为0。