让UIScrollView上的subView响应触摸事件
2016-08-25 18:01
246 查看
UIScrollView本身是无法处理touch事件的。所以要想让UIScrollView上的子view响应Touch事件有俩个思路:
第一, 就是重写这个子View类。
例如我要让UIScrollView上的UIImageView响应触摸事件,那我就写一个UIImageView的子类,在这个重定义的类里写代理方法响应触摸。
.h文件:
.m文件:
第二,可以写个UIScrollView的子类,把事件从UIScrollView传出去。
.h文件:
.m文件:
以上俩个方法都可以(貌似我用的第一个方法写的划得更流畅一些,至于原因,我现在也母鸡啊)
关于UIScrollView 原理 我看的这个链接:http://www.cocoachina.com/bbs/read.php?tid-40965-page-1.html 很厉害的样子。。。
第一, 就是重写这个子View类。
例如我要让UIScrollView上的UIImageView响应触摸事件,那我就写一个UIImageView的子类,在这个重定义的类里写代理方法响应触摸。
.h文件:
#import <UIKit/UIKit.h> @protocol ImageTouchDelegate<NSObject> -(void)imageTouch:(NSSet *)touches withEvent:(UIEvent *)event whichView:(id)imageView; @end @interface ImageTouchView : UIImageView @property(nonatomic,weak)id<ImageTouchDelegate> delegate; @end
.m文件:
- (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.userInteractionEnabled=YES; } return self; } - (BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view { return YES; } -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { if (_delegate && [_delegate respondsToSelector:@selector(imageTouch:withEvent:whichView:)]) { [_delegate imageTouch:touches withEvent:event whichView:self]; } }
第二,可以写个UIScrollView的子类,把事件从UIScrollView传出去。
.h文件:
#import <UIKit/UIKit.h> @interface ScrollTouchView : UIScrollView -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event; - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event; @end
.m文件:
@implementation ScrollTouchView - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.userInteractionEnabled=YES; } return self; } -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ [[self nextResponder]touchesBegan:touches withEvent:event]; [super touchesBegan:touches withEvent:event]; } - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{ [[self nextResponder]touchesMoved:touches withEvent:event]; [super touchesMoved:touches withEvent:event]; } @end
以上俩个方法都可以(貌似我用的第一个方法写的划得更流畅一些,至于原因,我现在也母鸡啊)
关于UIScrollView 原理 我看的这个链接:http://www.cocoachina.com/bbs/read.php?tid-40965-page-1.html 很厉害的样子。。。
相关文章推荐
- 解决 按钮响应延时[UIScrollView 和 UITableViewCell 中的子视图触摸事件延时]
- 让UIScrollView的子view响应触摸事件
- 成长小计-控制器中有UIScrollView控件时,无法响应触摸事件
- 让UIScrollView的子view响应触摸事件
- UIScrollView 响应触摸事件的机制
- UIScrollView不能响应touch事件的解决办法
- 关于UIScrollview不能响应touch事件的解决办法
- UIScrollView在有点击手势的情况下,会导致UITableView的cell点击事件无法响应
- ios UIScrollView不能响应TouchesBegin:的事件的解决办法
- ios UIScrollView不能响应TouchesBegin:的事件的解决办法
- iOS UITableView UIScrollView 的支持触摸事件
- ios UIScrollView不能响应TouchesBegin:的事件的解决办法
- ios UIScrollView响应点击事件
- 关于UIScrollView不能响应UITouch事件的解决办法
- 两个view重叠时如何只让上层view响应触摸事件
- [IOS]UIScrollView响应UITouch事件
- ios 中UIScrollView如何同时响应scrollViewDidScroll 与 touchesMoved等事件
- 『IOS』UIScrollView无法响应touch事件的解决办法
- UIScrollView不能响应UITouch事件的解决办法