求助scrollview内touch事件没反应

2025-05-07 14:39:56
推荐回答(2个)
回答(1):

UIScrollView本身无法处理touch事件要想实现,必须对UIScrollView上的subView做touch处理原理十分简单,好比要响应scrollView上的UIImageView,那么请创建一个UIImageVIew的子类,由这个自定义的UIImageView来处理touch事件头文件声明如下,供参考:#import @protocol ImageTouchDelegate-(void)imageTouch:(NSSet *)touches withEvent:(UIEvent *)event whichView:(id)imageView;@end@interface ImageTouchView : UIImageView { id delegate; BOOL delegatrue;}@property(nonatomic,assign)id delegate;@end这个是头文件,源文件可以是这个这样子@implementation ImageTouchView@synthesize delegate;-(id)initWithFrame:(CGRect)frame{ if (self == [super initWithFrame:frame]) { [self setUserInteractionEnabled:YES]; delegatrue=YES; } return self;}- (BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view{ return YES;}-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ if (delegatrue) { [delegate imageTouch:touches withEvent:event whichView:self]; }

回答(2):

关于UIScrollView,UIImageView等控件不能响应touch事件,主要涉及到事件响应者链的问题,如果在UIScrollView,UIImageView等控件添加了子View,这样事件响应将会被UIScrollView,UIImageView等控件终止,而且这些控件的userInteractionEnabled属性默认的是NO,所以想要解决使用触摸事件,我通过两种方法进行解决。
方法一:
创建UIScrollView,UIImageView等控件的类别文件,将touch的四个方法进行父类方法重写:(创建Objective-C File文件,然后修改类型,创建对应的类别文件)
#import "UIScrollView+TouchEvent.h"

@implementation UIScrollView (TouchEvent)

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[[self nextResponder] touchesBegan:touches withEvent:event];
[super touchesBegan:touches withEvent:event];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[[self nextResponder] touchesMoved:touches withEvent:event];
[super touchesMoved:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[[self nextResponder] touchesEnded:touches withEvent:event];
[super touchesEnded:touches withEvent:event];
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[[self nextResponder] touchesEnded:touches withEvent:event];
[super touchesEnded:touches withEvent:event];
}
@end
方法二:通过给UIScrollView,UIImageView等控件添加手势,执行对应的方法
如:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

bgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 200, 400)];
bgScrollView.backgroundColor = [UIColor lightGrayColor];
//添加手势

UITapGestureRecognizer *tapGestureR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(updateImageVAction:)];
[bgScrollView setUserInteractionEnabled:YES];
[bgScrollView addGestureRecognizer:tapGestureR];
[self.view addSubview:bgScrollView];

textFie = [[UITextField alloc] initWithFrame:CGRectMake(50, 50, 100, 50)];
textFie.layer.borderWidth = 1;
[bgScrollView addSubview:textFie];

}
//手势执行的方法

-(void)updateImageVAction:(UITapGestureRecognizer *)tapGR
{
[textFie resignFirstResponder];
}