oc的uibutton按钮点击更改背景色处理
新加一个button
要求圆角 同时点击时变色,我这里采用颜色绘图方式,更改其背景图。
1.注意[btn.layer setMasksToBounds:YES];
这个可以避免四个圆角出现白边。
2.btn.layer.cornerRadius = 5.0f; 这个用于设置圆角
代码
.
// 新建一个button
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.selected = YES;
[btn addTarget:weakself action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[btn setImage:[UIImage imageNamed:@"icon_meet_add"] forState:UIControlStateNormal];
[btn setTitle:@"添加到日程" forState:UIControlStateNormal];
btn.titleLabel.font = [UIFont fontWithName:kMediumFont size:NormalFontSize];
[btn setTitleColor:[UIColor colorWithHexString:@"ea3939"] forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColor colorWithHexString:@"ffffff"]];
// [btn addTarget:weakself action:@selector(buttonBackGroundHighlighted:) forControlEvents:UIControlEventTouchDown];
// [btn addTarget:weakself action:@selector(buttonBackGroundNormal:) forControlEvents:UIControlEventTouchUpInside];
[btn.layer setBorderColor:[UIColor colorWithHexString:@"ea3939"].CGColor];
[btn setBackgroundImage:[weakself imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
[btn setBackgroundImage:[weakself imageWithColor:[UIColor colorWithHexString:@"ffebeb"]] forState :UIControlStateSelected|UIControlStateHighlighted];
[btn.layer setMasksToBounds:YES];
btn.layer.cornerRadius = 5.0f;
[btn.layer setBorderWidth:0.5];
btn.imageEdgeInsets = UIEdgeInsetsMake(0, btn.frame.size.width - btn.imageView.frame.origin.x - btn.imageView.frame.size.width - 5, 0, 0);
btn.titleEdgeInsets = UIEdgeInsetsMake(0, -(btn.frame.size.width - btn.imageView.frame.size.width ), 0, 0);
[addCalender addSubview:btn];
[btn makeConstraints:^(MASConstraintMaker *make) {
make.height.equalTo(@50);
make.width.equalTo(@(SCREEN_WIDTH - 60));
make.top.equalTo(addCalender.top).with.offset(40);
make.centerX.equalTo(addCalender.centerX);
}];
使用的方法
- (UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
// button1普通状态下的背景色
- (void)buttonBackGroundNormal:(UIButton *)sender
{
sender.backgroundColor = [UIColor whiteColor];
}
// button1高亮状态下的背景色
- (void)buttonBackGroundHighlighted:(UIButton *)sender
{
sender.backgroundColor = [UIColor colorWithHexString:@"ffebeb"];
}