在程序中我们往往需要两个视图之间传值,用delegate可以解决这个问题。
(1)定义delegate
#import <UIKit/UIKit.h>
@protocol SetPhotoDelegate <NSObject>
- (void)setPhoto:(UIImage *)photo;
@end
@interface PhotoDelegate : NSObject
@end
(2)在代理人的.h文件中声明遵守该协议
#import "PhotoDelegate.h"
@interface ViewController : UIViewController<SetPhotoDelegate>
然后在.m文件中实现协议中的方法
- (void)setPhoto:(UIImage *)photo
{
//委托人实现委托方法
//显示照片
self.firstImageView.image = photo;
}
最后在初始化委托人的地方,将代理人设置为自己
PhotoPickerViewController *photoPicker = [self.storyboard instantiateViewControllerWithIdentifier:@"PhotoPicker"];
//将自己设为PhotoPickerViewController的委托人
photoPicker.delegate = self;
[self presentViewController:photoPicker animated:YES completion:NULL];
(3)在委托人头文件文件中定义
#import <UIKit/UIKit.h>
#import "PhotoDelegate.h"
@interface PhotoPickerViewController : UIViewController
//这是用assign防止引起循环引用
@property(nonatomic, assign) NSObject<SetPhotoDelegate> * delegate;
@end
- (IBAction)clickDoneButton:(id)sender
{
//通过delegate调用代理方法
[self.delegate setPhoto:selectedImage];
[self dismissViewControllerAnimated:YES completion:nil];
}