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

本文详细介绍了在iOS应用中使用UIButton实现按钮背景颜色切换的两种方法:直接调用touchDown方法和将颜色转换为图片。通过代码示例展示了如何在按钮点击时改变其背景颜色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天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 就这样

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值