標籤:
IOS 委託和協議區別和聯絡 (=)
上一片大致說了一下IOS上面委託和協議的區別和聯絡,並且舉了一個簡單的例子,但是例子比較簡單,今天做一個用委託類比button回調的例子。
在一個自訂View上面放一個登陸按鈕,並且這個LoginView裡面有一個實現ILogin的委派物件,在登陸按鈕的點擊事件中調用需要實現的協議函數。在一個ViewController中實現ILgin協議,並實現login方法。將自訂LoginView放到ViewController中,這時候點擊button按鈕,回自動調用login方法;這時候在ViewController中並沒有看到直接調用login方法的地方,好像系統的回調一樣。
代碼實現:
ILogin.h
?
| 1 2 3 4 5 6 7 8 9 10 |
#import <Foundation/Foundation.h> @protocol ILogin <NSObject> @required - ( void )login; @optional @end |
自訂View LoginView
?
| 1 2 3 4 5 6 7 |
#import <UIKit/UIKit.h> #import "ILogin.h" @interface LoginView : UIView @property (nonatomic)id<ILogin> delegate; @end |
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#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]; } @end |
ViewController
?
| 1 2 3 4 5 6 |
#import <UIKit/UIKit.h> #import "ILogin.h" @interface ViewController : UIViewController<ILogin> @end |
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#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] 實現協議函數調用!
現在你看到的現象好像是系統自動回調,但這是利用button按鈕的系統回調在出現的,正常情況下我們一般是通過在實現協議的對象(ViewController)中聲明委託人(LoginView)的對象,然後直接調用委託人的方法來實現回調,(註:委託人的方法中包含需要實現的協議方法)。這種方式應該是在IOS開發中經常用到的委託和協議組合。
? IOS 委託和協議區別和聯絡 (=)