根据按下的按钮,使用UIImagePickerController更改正确按钮的图像

时间:2013-05-07 21:35:36

标签: iphone ios uibutton

这是问题所在: 我希望用户点击一个按钮,然后选择按钮代表的图像。有多个按钮,用户可以选择为他/她点击的每个按钮选择不同的图像或相同的图像。 如何在void方法中添加if结构以检查按下了哪个按钮?

@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];


}

先谢谢,是的,我对这门语言很陌生。

2 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分:0)

-(IBAction)Buttonclicked:(id)sender中,点击的按钮是 sender。所以现在你知道点击了什么按钮。

所以现在唯一的问题是如何在不同的方法中引用sender

这就是实例变量的原因。您必须准备UIButton实例变量或属性。我们称之为theButton。然后在Buttonclicked:中,您将设置 theButton(至sender)。在任何其他方法中,您可以获取 theButton并执行您喜欢的任何操作。