更改UIButton背景颜色

时间:2012-03-16 12:46:44

标签: objective-c

我正在以编程方式创建按钮。我想改变按钮背景颜色,同时再次触摸内部,它必须在抬起我的手指后恢复其通常的颜色.....

nine = [UIButton buttonWithType:UIButtonTypeCustom];
[nine setFrame:CGRectMake(15, 105, 65, 40)];
[nine setTitle:@"9" forState:UIControlStateNormal];
[nine setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[nine setBackgroundColor:[UIColor cyanColor]];
[nine addTarget:self action:@selector(clickDigit:) forControlEvents:UIControlEventTouchUpInside];
[nine addTarget:self action:@selector(changeButtonBackGroundColor:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:nine];

//更改背景颜色

-(void)changeButtonBackGroundColor:(id) sender
{
    [nine setBackgroundColor:[UIColor redColor]];
}

这里创建了changeBackgroundColor方法来改变该按钮的颜色。它改变了颜色。

2 个答案:

答案 0 :(得分:14)

不知道这是否与您的问题有关,但是: 此

[nine setBackgroundColor:[UIColor redColor]];

应该是

[sender setBackgroundColor:[UIColor redColor]];

编辑: 改变这个

[nine addTarget:self action:@selector(changeButtonBackGroundColor:) forControlEvents:UIControlEventTouchUpInside];

[nine addTarget:self action:@selector(changeButtonBackGroundColor:) forControlEvents:UIControlEventTouchDown];
[nine addTarget:self action:@selector(resetButtonBackGroundColor:) forControlEvents:UIControlEventTouchUpInside];
[nine addTarget:self action:@selector(resetButtonBackGroundColor:) forControlEvents:UIControlEventTouchUpOutside];
[nine addTarget:self action:@selector(resetButtonBackGroundColor:) forControlEvents:UIControlEventTouchCancel];

并添加方法:

- (void)resetButtonBackGroundColor: (UIButton*)sender {
    [sender setBackgroundColor:[UIColor cyanColor]];
}

答案 1 :(得分:3)

我认为你有两种选择..

<强>首先

你可以把 [nine setBackgroundColor:[UIColor redColor]]; 放在“clickDigit”里面(和dasdom说重命名为发件人并改为(UIButton *)发件人)..

更改

[nine addTarget:self action:@selector(changeButtonBackGroundColor:) forControlEvents:UIControlEventTouchUpInside];

[nine addTarget:self action:@selector(changeButtonBackGroundColor:) forControlEvents:UIControlEventTouchUpOutside];

和方法“changeButtonBackGroundColor”

[sender setBackgroundColor:[UIColor cyanColor]];

<强>第二

创建通用UIControlEvents

[nine addTarget:self action:@selector(changeButtonBackGroundColor:) forControlEvents:UIControlEventAllEvents];

-(void)changeButtonBackGroundColor:(UIButton*) sender{
if ([sender.backgroundColor isEqual:[UIColor redColor]]){
    [sender setBackgroundColor:[UIColor cyanColor]];
}else{
    [sender setBackgroundColor:[UIColor redColor]];        
}}

我没有尝试此代码