IOS 委托和协议区别和联系 (=) 3年前

上一片大致说了一下IOS上面委托和协议的区别和联系,并且举了一个简单的例子,但是例子比较简单,今天做一个用委托模拟button回调的例子。

在一个自定义View上面放一个登陆按钮,并且这个LoginView里面有一个实现ILogin的委托对象,在登陆按钮的点击事件中调用需要实现的协议函数。在一个ViewController中实现ILgin协议,并实现login方法。将自定义LoginView放到ViewController中,这时候点击button按钮,回自动调用login方法;这时候在ViewController中并没有看到直接调用login方法的地方,好像系统的回调一样。

代码实现:

ILogin.h

#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];
}

@end

ViewController

#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] 实现协议函数调用!

现在你看到的现象好像是系统自动回调,但这是利用button按钮的系统回调在出现的,正常情况下我们一般是通过在实现协议的对象(ViewController)中声明委托人(LoginView)的对象,然后直接调用委托人的方法来实现回调,(注:委托人的方法中包含需要实现的协议方法)。这种方式应该是在IOS开发中经常用到的委托和协议组合。

飞奔的白菜
迢迢牵牛星,皎皎河汉女。
3
发布数
2
关注者
1024
累计阅读

热门教程文档

10.x
88小节
React Native
40小节
Objective-C
29小节
Kotlin
68小节
Djiango
17小节