您的位置:首页 > 产品设计 > UI/UE

让UIScrollView上的subView响应触摸事件

2016-08-25 18:01 246 查看
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 很厉害的样子。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息