Matt104
Matt104

Reputation: 79

How to share UIImagepickercontroller code for 2 buttons

In my project I am using the UIIamgepickercontroller to select an image from the library and load it into a UIImageView. I am doing this for 2 images so I have two buttons for each image view, but I do not want to replicate the code for image picker twice and I'm not sure how to implement so that the method knows which image view to load the image into. I think I need to use button tags? but can't find the right method.

here's my code:

.h

`#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

@interface LoadViewController : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate> {
    IBOutlet UIImageView *imageView;
    IBOutlet UIImageView *imageView2;
}

- (IBAction)pick1;
- (IBAction)pick2; 
- (void) getImage;


@end`

.m

#import "LoadViewController.h"

@implementation LoadViewController

UIImage *imageHandle;

- (IBAction)pick2 {

    [self getImage];
    imageView2.image = imageHandle;
}

- (IBAction)pick1{

    [self getImage];
    imageView.image = imageHandle;
}

- (void)getImage {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentModalViewController:picker animated:YES];

}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    imageHandle = image;
    [picker.parentViewController dismissModalViewControllerAnimated:YES];

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker.parentViewController dismissModalViewControllerAnimated:YES];
}

@end

Another problem I'v been having is that the methods to catch whether I have selected an image or cancelled the view do not seem to work although if I comment out the entire method (void)imagePickerControllerDidCancel then it will cancel?!?

I'm in the early stages of learning this stuff and any help would be very much appreciated!

Thanks

Upvotes: 0

Views: 420

Answers (1)

matt
matt

Reputation: 534977

You can identify the button with a tag (you can set this in Interface Builder), which is an arbitrary integer. The problem is that you've rejected the chance to receive a reference to the sender (the button); instead of - (IBAction)pick1, say - (IBAction)pick1:(id)sender. Now you can check the sender's tag (cast the sender to a UIView* so the compiler understands what you're doing).

Upvotes: 1

Related Questions