您的位置:首页 > 移动开发 > IOS开发

iOS每日一记之---------改变Btn点击时的背景颜色

2015-08-13 17:25 726 查看
今天UI设计师妹纸让我改变按钮的背景颜色 但是并没有给我图片。。。。于是我就上网找了一下 大体上有俩种方法实现 一个是调用按钮的 touchDown方法;另一个是把颜色装换成图片

废话不多说 上代码

UIButton *securitycodeButton = [UIButton buttonWithType:UIButtonTypeCustom];

securitycodeButton.frame = CGRectMake(DCS_SCREEN_W-100, 232, 90, 30);

self.securitycodeButton = securitycodeButton;

securitycodeButton.backgroundColor = DCS_COLOR_hui_background_color;//这个是Btn没有选择状态的背景颜色

[securitycodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];

[securitycodeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

securitycodeButton.titleLabel.font = [UIFont systemFontOfSize:12];

[securitycodeButton addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];//按钮点击时触发的方法

这里添加一个按钮的 touchDown方法就实现了

[securitycodeButton addTarget:self action:@selector(didBtnColorChange:) forControlEvents:UIControlEventTouchDown];

//点击按钮方法的实现

- (void)btnClick:(UIButton *)securitycodeButton

{

securitycodeButton.backgroundColor = DCS_COLOR_hui_background_color; //依旧写上没有选择时候的颜色

}

//实现按钮的touchDown方法

-(void)didBtnColorChange:(UIButton *)securitycodeButton

{

securitycodeButton.backgroundColor =DCSColor(211, 211, 211); //这里写上你想要改变的颜色就行了

}

方法二是把颜色装换成image 然后调用setbackgroundimage这个方法

//颜色转换成image

- (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;

}

UIImage *image = [self imageWithColor: //这里填入你要改变的颜色即可];

OK 就这样
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: