上一片大体说了一下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