2013-08-23 80 views

回答

5

.h文件中

UIButton *button; 
BOOL clicked; 

.m文件 - (無效)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

沒有必要伊瓦爾布爾,按鈕已選定,突出顯示和正常狀態內置到他們。

- (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選擇器處理狀態更改。

相關問題