在autolayout中加入每个view的weight,这样相互之间的关系就更明确,比如:
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];
代码更加简介,但这适用于一些特定的场合