我是靠谱客的博主 包容黑夜,最近开发中收集的这篇文章主要介绍protocol的简单写法,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

 1 //
 2 //
TouchView.h
 3 //
LessonUIControlAndSubClass
 4
 5
 6
 7 #import <UIKit/UIKit.h>
 8
 9 @class TouchView;
10 //1.制定协议,协议名字格式:类名+Delegate
11 @protocol TouchViewDelegate <NSObject>
12
13 @optional
14 - (void)touchBegan:(TouchView *)touchView;
15 - (void)touchMoved:(TouchView *)touchView;
16 - (void)touchEnded:(TouchView *)touchView;
17 - (void)touchCancelled:(TouchView *)touchView;
18
19 @end
20
21 @interface TouchView : UIView
22
23 //2.写属性,属性名delegate,类型是id,并且要遵守协议<类名Delegate>
24 @property (assign, nonatomic) id<TouchViewDelegate> delegate;
25
26 @end

 1 //
 2 //
TouchView.m
 3 //
LessonUIControlAndSubClass
 4 //
 5
 6 #import "TouchView.h"
 7
 8 @implementation TouchView
 9
10 //3.一旦找到代理,让代理执行事情
11 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
12
//判断delegate是否实现了某方法
13
if ([_delegate respondsToSelector:@selector(touchBegan:)]) {
14 
[_delegate touchBegan:self];
15 
}
16 }
17
18 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
19
if ([_delegate respondsToSelector:@selector(touchMoved:)]) {
20 
[_delegate touchMoved:self];
21 
}
22 }
23
24 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
25
if ([_delegate respondsToSelector:@selector(touchEnded:)]) {
26 
[_delegate touchEnded:self];
27 
}
28 }
29
30 - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
31
if ([_delegate respondsToSelector:@selector(touchCancelled:)]) {
32 
[_delegate touchCancelled:self];
33 
}
34 }
35
36 @end

 

转载于:https://www.cnblogs.com/jiangdaohong/p/4596873.html

最后

以上就是包容黑夜为你收集整理的protocol的简单写法的全部内容,希望文章能够帮你解决protocol的简单写法所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(53)

评论列表共有 0 条评论

立即
投稿
返回
顶部