ViewController.h
Here we make sure to import the right frameworks, hold a UIImage and the ProfileUIView instance. We also declare a method to pick an image, which can be invoked, e.g., from a button on the corresponding view, when connected in Interface Builder:
#import <UIKit/UIKit.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "ProfileUIView.h"
@interface ViewController : UIViewController<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong) UIImage *profilePic;
@property (strong, nonatomic) IBOutlet ProfileUIView *profileUIView;
- (IBAction)pickImage:(id)sender;
@end
In ViewController.m we implement the method to pick an image and the delegate method that is invoked once the user has picked an image:
- (IBAction)pickImage:(id)sender {
UIImagePickerController *pickerC = [[UIImagePickerController alloc] init];
pickerC.delegate = self;
[self presentViewController:pickerC animated:YES completion:nil];
}
#pragma mark - UIImagePicker delegate methods
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[self dismissViewControllerAnimated:NO completion:nil];
NSString *mediaType = info[UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *) kUTTypeImage]) {
self.profilePic = [info objectForKey:UIImagePickerControllerOriginalImage];
[self.profileUIView setPicture:self.profilePic];
}
}
ProfileUIView.h
Here we declare the profile picture UIImage, the UIButton which shows the picture, and the method that sets the image:
#import <UIKit/UIKit.h>
@interface ProfileUIView : UIView
@property (nonatomic, retain) UIImage *profilePic;
@property (strong, nonatomic) IBOutlet UIButton *pictureButton;
- (void) setPicture:(UIImage *)image;
@end
ProfileUIView.m
Here we make sure that the UIButton is in place when we awake from NIB, and implement the set picture method to set the image as background of the UIButton:
#import "ProfileUIView.h"
@implementation ProfileUIView
-(void)awakeFromNib {
self.pictureButton = [[UIButton alloc] initWithFrame:self.bounds];
[self addSubview:self.pictureButton];
}
- (void) setPicture:(UIImage *)image {
self.profilePic = image;
[self.pictureButton setBackgroundImage:image forState:UIControlStateNormal];
}
@end
When pickImage is invoked on the main UIViewController, it stores the image from UIImagePicker into the profilePic property on the UIViewController and assigns the image using the original setPicture method.