2012-10-31 170 views
0

我使用的UIButton用XIB1和backgroundImage是check_box_off.png,同時點擊 atmbtn將backgroundImage變化check_box_on.png同時的NSLog打印yesString,再次點擊atmbtn存在和backgroundImage一樣沒有變化check_box_on.png NSLog的同時打印相同yesString僅..一次又一次無比的atmbutton同一只發生..如何更改UIButton backgroundimage,同時點擊相同的UIbutton?

- (IBAction)atmAction:(id)sender{ 
    if([atmbtn backgroundImageForState:UIControlStateNormal] == 
     [UIImage imageNamed:@"check_box_on.png"]) { 
     [atmbtn setImage:[UIImage imageNamed:@"check_box_off.png"] 
       forState:UIControlStateNormal]; 

     noString = @"No"; 
     NSLog(@"atm=%@",noString); 
    } else if([atmbtn backgroundImageForState:UIControlStateNormal] == 
       [UIImage imageNamed:@"check_box_off.png"]) { 

     [atmbtn setImage:[UIImage imageNamed:@"check_box_on.png"] 
       forState:UIControlStateNormal]; 

     yesString = @"Yes"; 
     NSLog(@"atm = %@",yesString); 
    } 
} 

輸出:

的NSLog打印:

大氣壓=是

大氣壓=是

大氣壓=是

我怎麼能解決這個問題?請分享您的想法。

回答

1

使用本:

[atmbtn setBackgroundImage:[UIImage imageNamed:@"check_box_on.png"] forState:UIControlStateNormal]; 
+0

這是行之有效的...感謝您的想法 –

+0

歡迎PLZ接受這個答案... –

+0

它的工作很好... Tanx的想法.. –

0

設置一個布爾變量,而不是如果條件

.h文件中

BOOL _isClicked; 

.m文件

-(IBAction)atmAction:(id)sender{ 

    if(!isClicked){ 

     [atmbtn setImage:[UIImage imageNamed:@"check_box_off.png"] 
       forState:UIControlStateNormal]; 
     _isClicked = YES;  

    } else { 

     [atmbtn setImage:[UIImage imageNamed:@"check_box_on.png"] 
       forState:UIControlStateNormal];  
      _isClicked = NO; 
    } 
} 
0

要設置UIImage和你正在檢查backgroundImage

嘗試

​​

,而不是

if([atmbtn backgroundImageForState:UIControlStateNormal] == 
    [UIImage imageNamed:@"check_box_on.png"]) 
+0

它的工作良好...我被設置爲UIButton backgroundImage check_box_off.png圖像,但我嘗試了圖像路徑。 –

0

您可以簡單地使用

[atmbtn setBackgroundImage:[UIImage imageNamed:@"check_box_off.png"] 
        forState:UIControlStateNormal]; 
    [atmbtn setBackgroundImage:[UIImage imageNamed:@"check_box_on.png"] 
        forState:UIControlStateSelected]; 

其中atmbtn是xib中按鈕的出口。

+0

它的工作很好...我被設置爲check_box_off。PNG圖像作爲UIButton backgroundImage,但我試過圖像路徑。我用[atmbtn setBackgroundImage:[UIImage imageNamed:@「check_box_off.png」] forState:UIControlStateNormal];而不是[atmbtn setImage:[UIImage imageNamed:@「check_box_off.png」] forState:UIControlStateNormal]; –

0

嗨試試isEqual方法而不是==,因爲你比較的對象不是值。試試這個:

-(IBAction)atmAction:(id)sender{ 

    if([[atmbtn imageForState:UIControlStateNormal] 
      isEqual:[UIImage imageNamed:@"check_box_on.png"]]) { 

     [atmbtn setImage:[UIImage imageNamed:@"check_box_off.png"] 
       forState:UIControlStateNormal]; 
     noString = @"No"; 
     NSLog(@"atm = %@",noString); 

    } else if([[atmbtn imageForState:UIControlStateNormal] 
        isEqual:[UIImage imageNamed:@"check_box_off.png"]]){ 

     [atmbtn setImage:[UIImage imageNamed:@"check_box_on.png"] 
       forState:UIControlStateNormal]; 

     yesString = @"Yes"; 
     NSLog(@"atm = %@",yesString); 
    } 
}