让UIScrollView上的subView响应触摸事件

来源:互联网 发布:常州软件开发公司 编辑:程序博客网 时间:2024/05/29 04:36

UIScrollView本身是无法处理touch事件的。所以要想让UIScrollView上的子view响应Touch事件有俩个思路:

第一, 就是重写这个子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 很厉害的样子。。。

0 0
原创粉丝点击