delegate设计模式

delegate设计模式

1.代理

三方:委托方、代理方、协议

 2.定义协议

协议:一堆方法的声明(面试题)

#import <UIKit/UIKit.h>

#warning 1.定义协议
@class TouchView;
@protocol TouchViewDelegate <NSObject>

@optional
// touchView开始被点击
- (void)touchViewBeginTouched:(TouchView *)touchView;

// touchView结束被点击
- (void)touchViewEndTouched:(TouchView *)touchView;

@end

@interface TouchView : UIView

#warning 2.给外界提供设置Delegate属性的接口
// 在定义Delegate属性时,需要使用assign关键字,防止产生循环引用。
@property(nonatomic, assign)id<TouchViewDelegate>delegate;

@end

  

#import "RootViewController.h"
#import "TouchView.h"

#warning 4.接受协议
@interface RootViewController () <TouchViewDelegate>

@end

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    TouchView *touchView = [[TouchView alloc] initWithFrame:CGRectMake(130, 100, 100, 100)];
    touchView.backgroundColor = [UIColor redColor];
    
#warning 3.给Delegate属性赋值
    touchView.delegate = self;
    
    [self.view addSubview:touchView];
    [touchView release];
}

#warning 5.实现协议中的方法
#pragma mark - TouchViewDelegate
- (void)touchViewBeginTouched:(TouchView *)touchView
{
    self.view.backgroundColor = [UIColor greenColor];
}

- (void)touchViewEndTouched:(TouchView *)touchView
{
    touchView.backgroundColor = [UIColor colorWithRed:(arc4random() % 256 / 255.0) green:(arc4random() % 256 / 255.0) blue:(arc4random() % 256 / 255.0) alpha:1];
}

  

#import "TouchView.h"

@implementation TouchView

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
#warning 6.在对应的时间点让Delegate去执行协议中对应的方法
    if (_delegate && [_delegate respondsToSelector:@selector(touchViewBeginTouched:)]) // 判断协议存在,且方法被实现了 
    {
        [_delegate touchViewBeginTouched:self];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (_delegate && [_delegate respondsToSelector:@selector(touchViewEndTouched:)])
    {
        [_delegate touchViewEndTouched:self];
    }
}

  

转载于:https://www.cnblogs.com/sqdhy-zq/p/4764479.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值