我的iOS学习历程 - TargetAction
2015-11-14 10:32
477 查看
什么是TargetAction?比如button继承于view,button可以通过添加点击事件来做出反应,但是view却不行,怎么让view也可以和button一样呢,这就是TargetAction的作用了:
首先我们自定义一个buttonView:buttonView最重要的是需要两个属性:
1.action:需要实现的方法
2.target:谁来响应这个方法
所以我们需要重写初始化方法,把这两个属性添加进去(我们默认是关闭ARC以便于熟悉内存管理)
- (instancetype)initWithFrame:(CGRect)frame target:(id)target action:(SEL)action { self = [super initWithFrame:frame]; if (self) { // 初始化时 对属性 进行赋值 self.action = action; self.target = target; }return self; }
接下来就是写方法,要在点击结束是执行命令的话:(四个方法尽量写全)
重点:让某个对象调用某个方法用哪个参数用 performSelector这个方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { // 使用self.target对象调用action方法 // 让一个对象去调用这个对象类里面的方法 // Object 可携带的参数 [self.target performSelector:self.action withObject:self]; } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { }
这样我们一个具备button点击功能的view就好了,让我们来试试让这个view在点击后改变颜色:
1.先创建一个buttonView:
target填self就是自己来响应后面填的buttonViewClick这个方法
ButtonView *buttonView = [[ButtonView alloc] initWithFrame:CGRectMake(100, 100, 100, 100) target:self action:@selector(buttonViewClick:)];
2.接下来写改变颜色的方法:
- (void)buttonViewClick:(ButtonView *)buttonView{ buttonView.backgroundColor = [UIColor colorWithRed:arc4random()%256 / 255.0 green:arc4random()%256 / 255.0 blue:arc4random()%256 / 255.0 alpha:1]; }
是不是很简单?
相关文章推荐
- 我的iOS学习历程 - TargetAction
- Xcode各版本官方下载及百度云盘下载, Mac和IOS及Xcode版本历史.
- Why BIOS loads MBR into 0x7C00 in x86 ?
- iOS缓存机制
- iOS开发规范
- iOS9.2 PCH文件的创建和使用
- ios学习笔记(四)定时器
- ios学习笔记(四)定时器
- iOS开发——学习runtime的理解和心得
- iOS开发——通过代码方式使用AutoLayout
- IOS流媒体播放器V1.1_rtsp、rmtp、m3u8、mms、mmsh
- IOS流媒体播放器V1.1_rtsp、rmtp、m3u8、mms、mmsh
- 三种实现iOS瀑布流的思路总结
- iOS巅峰之SBJSON解析
- IOS中实现图片点击全屏预览
- [iOS] 建立与使用Framework
- ios快捷键
- 初学IOS开发记录
- 单例设计模式
- Block语法及页面传值