代理设计模式,功能跟addTarget/action比较像但是也有一些不同:
先在AppDelegate.m中写入navigation,(用于push到下一个页面,模态也可以)
#import "AppDelegate.h"
#import "ViewController.h"@interface AppDelegate ()@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; ViewController *viewVC = [[ViewController alloc] init]; UINavigationController *naviVC = [[UINavigationController alloc] initWithRootViewController:viewVC]; self.window.rootViewController = naviVC; return YES;}
再建立一个SecondViewController
在SecondViewController.h中
#import <UIKit/UIKit.h>
//第一步:实现一个代理协议@protocol SecondViewControllerDelegate <NSObject>// 第二步:定义代理方法- (void)passValueToViewController:(NSString *)passValue;@end@interface SecondViewController : UIViewController// 第三步:声明代理人的属性// 代理人的属性一定要用assign修饰,防止的是父类对象作为子类对象代理人的时候引起的循环引用,造成内存泄漏// id<SecondViewControllerDelegate> 代表的是一个遵守了SecondViewControllerDelegate协议的泛型指针@property (nonatomic, assign) id<SecondViewControllerDelegate> delegate;@end接着在ViewController.m中
#import "ViewController.h"
#import "SecondViewController.h"//第四步: 遵守代理协议@interface ViewController ()<SecondViewControllerDelegate>@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; }- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ SecondViewController *secondVC = [[SecondViewController alloc] init]; // 第五步:指定“我自己(ViewController类)”为secondVC的代理人 secondVC.delegate = self; [self.navigationController pushViewController:secondVC animated:YES];}// 第六步:实现代理方法- (void)passValueToViewController:(NSString *)passValue{ // 第七步:使用传递过来的值 self.title = passValue; NSLog(@"passValue ===== %@", passValue);}最后在SecondViewController.m中
#import "SecondViewController.h"@interface SecondViewController ()@end@implementation SecondViewController- (void)viewDidLoad { [super viewDidLoad];}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ // 第八步: 首先判断代理人是否存在,其次判断代理人是否实现了代理方法,如果都做了,就让代理人去执行代理方法 if (self.delegate && [self.delegate respondsToSelector:@selector(passValueToViewController:)]) { // 第九步:让代理人执行代理方法,并传递参数 [self.delegate passValueToViewController:@"你好"]; }}