2013-05-07 88 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