UI - Delegate协议和代理

比target-action更为常用的是delegate,下面是如何定义一个协议:

#TouchView.h

#import <UIKit/UIKit.h>
// 1.以前在OC阶段学习Delegate时 涉及到几个方面?
// 三方: 委托方 代理方 协议

// 2.如何定义一个协议?
// 协议指的是一堆方法的声明(OC笔试题)
#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

#TouchView.m

#import "TouchView.h"

@implementation TouchView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
#warning 6.在对应的时间点让Delegate去执行协议当中对应的方法.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (_delegate && [_delegate respondsToSelector:@selector(touchViewBeginTouched:)])
    {
        [_delegate touchViewBeginTouched:self];
    }
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{

}

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

-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{

}

#RootViewController.m

#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实例对象 并且设置delegate
    TouchView *touchView = [[TouchView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    touchView.backgroundColor = [UIColor cyanColor];
#warning 3.给delegate属性赋值.
    touchView.delegate = self;
    [self.view addSubview:touchView];
    [touchView release];
}
#warning 5.实现协议中的方法
#pragma mark - TouchViewDelegate
// 3.assign ==> 循环引用 为什么会存在循环引用问题?
// 循环引用是指两个对象互相retain对方(你中有我,我中有你)
//-(void)touchViewBeginTouched:(TouchView *)touchView
//{
//    self.view.backgroundColor = [UIColor yellowColor];
//}

-(void)touchViewEndTouched:(TouchView *)touchView
{
    NSLog(@"haha");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值