0

我想为iphone制作一个应用程序。这是一个与此类似的 Nonogram:http ://www.puzzle-nonograms.com/如何使 UIButtons 将其颜色从白色变为黑色并反转?

4

2 回答 2

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;

    }



}

我希望它会有所帮助。祝你好运。。

于 2013-08-23T22:12:07.630 回答
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 选择器处理状态更改。

于 2013-08-23T23:50:00.603 回答