上一片大體說了一下IOS上面委託和協議的區別和聯繫,而且舉了一個簡單的例子,可是例子比較簡單,今天作一個用委託模擬button回調的例子。 ide
在一個自定義View上面放一個登錄按鈕,而且這個LoginView裏面有一個實現ILogin的委託對象,在登錄按鈕的點擊事件中調用須要實現的協議函數。在一個ViewController中實現ILgin協議,並實現login方法。將自定義LoginView放到ViewController中,這時候點擊button按鈕,回自動調用login方法;這時候在ViewController中並無看到直接調用login方法的地方,好像系統的回調同樣。 函數
代碼實現: ui
ILogin.h atom
#import <Foundation/Foundation.h> @protocol ILogin <NSObject> @required - (void)login; @optional @end自定義View LoginView
#import <UIKit/UIKit.h> #import "ILogin.h" @interface LoginView : UIView @property (nonatomic)id<ILogin> delegate; @end
#import "LoginView.h" @implementation LoginView - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // Initialization code UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button setFrame:CGRectMake(30, 60, 150, 45)]; [button setTitle:@"LoginView登錄" forState:UIControlStateNormal]; [button addTarget:self action:@selector(submitClick) forControlEvents:UIControlEventTouchUpInside]; [self addSubview:button]; } return self; } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { // Drawing code } */ - (void)submitClick{ //這裏注意,調用實現協議的類的login方法 [self.delegate login]; } @endViewController
#import <UIKit/UIKit.h> #import "ILogin.h" @interface ViewController : UIViewController<ILogin> @end
#import "ViewController.h" #import "LoginView.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. LoginView *loginView=[[LoginView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 300)]; loginView.delegate=self; [self.view addSubview:loginView]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark - ILogin 協議實現 - (void)login{ NSLog(@"實現協議函數調用!"); } @end
點擊button調用結果: 2013-08-08 19:49:43.974 DelegateDemo[2205:c07] 實現協議函數調用! spa
如今你看到的現象好像是系統自動回調,但這是利用button按鈕的系統回調在出現的,正常狀況下咱們通常是經過在實現協議的對象(ViewController)中聲明委託人(LoginView)的對象,而後直接調用委託人的方法來實現回調,(注:委託人的方法中包含須要實現的協議方法)。這種方式應該是在IOS開發中常常用到的委託和協議組合。 code