例如,咱们要在一个 ViewController 中使用一个ActionSheet,代码以下:this
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Delegate Example" delegate:self // telling this class to implement UIActionSheetDelegate cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Destructive Button" otherButtonTitles:@"Other Button",nil [actionSheet showInView:self.view];
中间的代码: delegate:self 来告诉当前这个ViewController 来实现 UIActionSheetDelegate
这样作的缘由是
ViewController 和 ActionSheet 两者是相互独立的,可是当用户点击了 ActionSheet 上的按钮时,ViewController 须要处理 ActionSheet 上按钮的点击事件,这样作至关于通知 ViewController 监听 UIActionSheetDelegate,以便咱们处理 ActionSheet 上按钮的点击事件。atom
注意:
delegte:self; 这行代码仅是告诉 ViewController 实现 UIActionSheetDelegate,可是咱们还须要告诉类实现 UIActionSheetDelegate protocol (协议),方法是在 .h 文件中 加入,以下所示:代理
@interface DelegateExampleViewController : UIViewController <UIActionSheetDelegate>
在CustomClass.h 文件中 首先要为这个 delegate 定义 protocol (写在 @interface 以前)
在 protocol 和 end 之间定义 protocol 方法, 这个方法能够被任何使用这个代理的类所使用code
#import @class CustomClass; //为Delegate 定义 protocol @protocol CustomClassDelegate //定义 protocol 方法 -(void)sayHello:(CustomClass *)customClass; @end @interface CustomClass : NSObject { } // define delegate property @property (nonatomic, assign) id delegate; // define public functions -(void)helloDelegate; @end
.m 文件中没什么特别的,最重要的要实现 helloDelegate 方法事件
-(void)helloDelegate { // send message the message to the delegate! [delegate sayHello:self]; }
接下来咱们切换到要使用这个类的 ViewController ,实现上面刚刚建立的 delegateit
// DelegateExampleViewController.h // import our custom class #import "CustomClass.h" @interface DelegateExampleViewController : UIViewController <CustomClassDelegate> { } @end
在 DelegateExampleViewController.m 文件中,咱们须要初始化这个 custom Class,而后让 delegate 给咱们传递一条消息io
//DelegateExampleViewController.m CustomClass *custom = [[CustomClass alloc] init]; // assign delegate custom.delegate = self; [custom helloDelegate];
仍是在 DelegateExampleViewController.m 咱们要实如今 custom Class.h 中生命的 delegate functionfunction
-(void)sayHello:(CustomClass *)customClass { NSLog(@"Hi!"); }
Bingo!class