//ZSYPopAdertiseView.m - initWithTitleImage:(NSString *)titleImage TitleValue:(NSString *)titleValue ActionImage:(NSString *)actionImage { self = [super init]; if (self) { self.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:defaultAlpha]; self.userInteractionEnabled = YES; _leftImageView = [[UIImageView alloc] init]; _leftImageView.image = [UIImage imageNamed:titleImage]; _contentLabel = [[UILabel alloc] init]; _contentLabel.numberOfLines = 0; _contentLabel.text = titleValue; _contentLabel.font = [UIFont systemFontOfSize:defaultFontSize]; _contentLabel.textColor = [UIColor whiteColor]; _actionButton = [UIButton buttonWithType:UIButtonTypeCustom]; [_actionButton setImage:[UIImage imageNamed:actionImage] forState:UIControlStateNormal]; [self addSubview:_leftImageView]; [self addSubview:_contentLabel]; [self addSubview:_actionButton]; //对全部subviews设置约束 [self initSubviews]; } return self; }
//设置subviews的约束 - (void)initSubviews { @weakify(self); //左侧图标 [_leftImageView mas_makeConstraints:^(MASConstraintMaker *make) { @strongify(self); make.centerY.mas_equalTo(self.mas_centerY); make.height.mas_equalTo(self.leftImageView.image.size.height); make.left.mas_equalTo(self.mas_left).offset(defaultLeftPadding); make.width.mas_equalTo(self.leftImageView.image.size.width); }]; //中间UILabel [_contentLabel mas_makeConstraints:^(MASConstraintMaker *make) { @strongify(self); make.centerY.mas_equalTo(self.mas_centerY); make.left.mas_equalTo(self.leftImageView.mas_right).offset(defaultPerPadding); make.right.mas_equalTo(self.actionButton.mas_left).offset(-defaultPerPadding); }]; //右侧图标 [_actionButton mas_makeConstraints:^(MASConstraintMaker *make) { @strongify(self); make.centerY.mas_equalTo(self.mas_centerY); make.right.mas_equalTo(self.mas_right).offset(-defaultPerPadding); make.width.mas_equalTo(self.actionButton.imageView.image.size.width); make.height.mas_equalTo(self.actionButton.imageView.image.size.height); }]; //注意:根据UILabel.text,再更新中间UILabel的高度 [self mas_makeConstraints:^(MASConstraintMaker *make) { make.bottom.mas_equalTo(self.contentLabel.mas_bottom); }]; [_actionButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside]; }
注意:ide
UILabel若是须要高度动态改变 ,设置约束时就不要设置 height约束spa