代码实现自动布局
直接上代码
UIImage *icon = [UIImage imageNamed:menu.menuIcon];
CGSize menuIconSize = icon.size;
NSLayoutConstraint *menuIconYConstraint = [NSLayoutConstraint constraintWithItem:_menuIcon attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeCenterY multiplier:1.0f constant:0.0f];
NSLayoutConstraint *menuIconLeftConstraint = [NSLayoutConstraint constraintWithItem:_menuIcon attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeLeading multiplier:1.0f constant:20.0f];
NSLayoutConstraint* menuIconHeightConstraint = [NSLayoutConstraint constraintWithItem:_menuIcon attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:menuIconSize.height];
NSLayoutConstraint* menuIconWidthConstraint = [NSLayoutConstraint constraintWithItem:_menuIcon attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:menuIconSize.width];
[_menuIcon setTranslatesAutoresizingMaskIntoConstraints:NO];
menuIconYConstraint.active = YES;
menuIconLeftConstraint.active = YES;
menuIconHeightConstraint.active = YES;
menuIconWidthConstraint.active = YES;
CGSize menuNameSize = [NSString stringSizeWithText:menu.menuName andMaxSize:CGSizeMake(MAXFLOAT, MAXFLOAT) andFont:[UIFont systemFontOfSize:14]];
NSLayoutConstraint *menuNameYConstraint = [NSLayoutConstraint constraintWithItem:_menuName attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
NSLayoutConstraint *menuNameLeftConstraint = [NSLayoutConstraint constraintWithItem:_menuName attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.menuIcon attribute:NSLayoutAttributeRight multiplier:1.0 constant:20];
NSLayoutConstraint *menuNameWithContraint = [NSLayoutConstraint constraintWithItem:_menuName attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:menuNameSize.width];
NSLayoutConstraint *menuNameHeightContraint = [NSLayoutConstraint constraintWithItem:_menuName attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:menuNameSize.height];
[_menuName setTranslatesAutoresizingMaskIntoConstraints:NO];
menuNameYConstraint.active = YES;
menuNameWithContraint.active = YES;
menuNameLeftConstraint.active = YES;
menuNameHeightContraint.active = YES;