2013-05-07 127 views
1

這是問題: 我希望用戶點擊按鈕並選擇按鈕所代表的圖像。有不止一個按鈕,用戶可以選擇不同的圖像,或者他/她點擊的每個按鈕都選擇相同的圖像。 如何在void方法中添加一個if結構來檢查哪個按鈕被按下?根據按下哪個按鈕,使用UIImagePickerController更改正確按鈕的圖像

@implementation ViewController 
@synthesize tegelEen,tegelTwee; //tegelEen is a button an so is tegelTwee 

-(IBAction)Buttonclicked:(id)sender { 
    picController = [[UIImagePickerController alloc]init]; 
    picController.delegate = self; 
    picController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 

    [self presentViewController:picController animated:YES completion:nil]; 

} 



-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { 

    UIImage *btnImage = [info objectForKey:UIImagePickerControllerOriginalImage]; 

     //Now it changes both buttons but I want it to change only the one that was clicked. 
     [tegelEen setImage:btnImage forState:UIControlStateNormal]; 
     [tegelTwee setImage:btnImage forState:UIControlStateNormal]; 

    [self dismissViewControllerAnimated:YES completion:nil]; 


} 

在此先感謝,是的,我對這種語言很新。

回答

0

-(IBAction)Buttonclicked:(id)sender,按鈕點擊sender。所以現在你知道按鈕被點擊了。

所以現在唯一的問題是如何從不同的方法中引用sender

這就是爲什麼有實例變量。你必須準備一個UIButton實例變量或屬性。我們稱之爲theButton。然後在Buttonclicked:你會theButton(到sender)。在任何其他方法中,您可以得到theButton並做任何你喜歡的事情。

+0

這正是我一直在尋找的,感謝噸:D – 2013-05-08 22:27:38

0

只需按住按鈕的標籤即可。例如,;

@implementation ViewController 
@synthesize tegelEen,tegelTwee; //tegelEen is a button an so is tegelTwee 
int lastClickedButtonTag; 

- (void)viewDidLoad 
{ 
    tegelEen.tag = 1; 
    tegelTwee.tag = 2; 
} 

-(IBAction)Buttonclicked:(UIButton *)sender 
{ 
    lastClickedButtonTag = sender.tag; 

    picController = [[UIImagePickerController alloc]init]; 
    picController.delegate = self; 
    picController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 

    [self presentViewController:picController animated:YES completion:nil]; 
} 

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
{ 
    UIImage *btnImage = [info objectForKey:UIImagePickerControllerOriginalImage]; 

    //Now it changes the button that was clicked. 

    if (lastClickedButtonTag == 1) [tegelEen setImage:btnImage forState:UIControlStateNormal]; 
    else if (lastClickedButtonTag == 2) [tegelTwee setImage:btnImage forState:UIControlStateNormal]; 

    [self dismissViewControllerAnimated:YES completion:nil]; 
} 
+0

謝謝你的努力,但我更喜歡答案:) – 2013-05-08 22:28:08