我想为iPhone制作应用程序。这是一个与此类似的Nonogram:http://www.puzzle-nonograms.com/如何让UIButtons的颜色从白色变为黑色并反转?
答案 0 :(得分:5)
.h文件
UIButton *button;
BOOL clicked;
.m文件 - (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
clicked=YES;
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(changeBtnColor)
forControlEvents:UIControlEventTouchDown];
[button setTitle:@" 1 " forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[self.view addSubview:button];
}
-(void)changeBtnColor{
if (clicked) {
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
clicked=NO;
}
else{
[button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
clicked=YES;
}
}
我希望它会有所帮助。祝你好运..
答案 1 :(得分:1)
无需ivar布尔值,按钮已选中,突出显示并且内置了正常状态。
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:CGRectMake(0, 0, 320, 50)];
[button addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Normal State" forState:UIControlStateNormal];
[button setTitle:@"Selected State" forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:@"normal_image"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"selected_image"] forState:UIControlStateSelected];
[self.view addSubview:button];
}
-(void)buttonPress:(UIButton *)button{
button.selected = !button.selected;
//do your other code here for button selection
}
否则在界面构建器中设置按钮状态,只需让buttonPress选择器处理状态更改。