在autolayout中加入每一個view的weight,這樣相互之間的關係就更明確,好比:spa
double iconViewWeight = 1; double titleLabelWeight = 12; double timeLabelWeight = 3; double standardWeigth = iconViewWeight; double iconViewWeightRatio = iconViewWeight / standardWeigth; double titileLabelWightRatio = titleLabelWeight / standardWeigth; double timeLabelWightRatio = timeLabelWeight / standardWeigth; UIView *standardView = _iconView; NSDictionary *views = NSDictionaryOfVariableBindings(_iconView, _titileLabel, _timeLabel, bgImageView); NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:_iconView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:standardView attribute:NSLayoutAttributeWidth multiplier:iconViewWeightRatio constant:0.0f]; [self addConstraint:constraint]; constraint = [NSLayoutConstraint constraintWithItem:_titileLabel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:standardView attribute:NSLayoutAttributeWidth multiplier:titileLabelWightRatio constant:0.0f]; [self addConstraint:constraint]; constraint = [NSLayoutConstraint constraintWithItem:_timeLabel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:standardView attribute:NSLayoutAttributeWidth multiplier:timeLabelWightRatio constant:0.0f]; [self addConstraint:constraint]; constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"|-[_iconView]-[_titileLabel]-[_timeLabel]-|" options:NSLayoutFormatAlignAllCenterY metrics:nil views:views]; [self addConstraints:constraints]; constraint = [NSLayoutConstraint constraintWithItem:_iconView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0f]; [self addConstraint:constraint];
代碼更加簡介,但這適用於一些特定的場合code