//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