iOS scrollView与touchesBegan等冲突的解决办法

本人在控制器重写了3个方法,touchesBegan,touchesMoved 和touchesEnded,控制器中有一个 scrollView,最后的结果是那3个方法都不走,原因是被scrollView拦截了。
有一种办法是设置scrollView.userInteractionEnabled = NO,关闭交互就会走那3个方法,但是这种方法不太好,因为scrollView自身一般都会有其它交互。
在网上查了一些方法,大概有2种:
第一种:自定义一个scrollView,然后在自定义的scrollView中,重写那3个方法
第二种:写一个 scrollView的分类,如UIScrollView+Touch ,在分类中重写那3个方法,如:

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

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

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

网上的这种做法管不管用?应该说管用一部分,因为网上紧紧是针对touchesBegan这一个方法而言,只要在子类或者分类中重写了那3个方法,控制器的touchesBegan就会触发。
但是,我要的是控制器的那3个方法都要走,而且走的流畅。现在按照网上的这种做法,现象是,touchesBegan和touchesEnded会走,然而touchesMoved走得不流畅,不管你的手指移动多长的距离,touchesMoved通常只走一次,偶尔2次,这是为什么?
我们来分析一下,子类和分类中重写的那3个方法中,[self nextResponder]指的是谁?指的应该是控制器的view,而不是控制器,控制器的view的下一个响应者才是控制器,所以不应该写[self nextResponder],应该写[[self nextResponder] nextResponder],如:

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

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

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

或者在分类中重写那3个方法,然后super一下也是没问题的,注意是分类,不是子类

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesMoved:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesCancelled:touches withEvent:event];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • //www.greatytc.com/p/855e5e09cbdd
    指尖的跳动阅读 3,816评论 0 0
  • 好奇触摸事件是如何从屏幕转移到APP内的?困惑于Cell怎么突然不能点击了?纠结于如何实现这个奇葩响应需求?亦或是...
    Lotheve阅读 59,036评论 51 604
  • 在iOS开发中经常会涉及到触摸事件。本想自己总结一下,但是遇到了这篇文章,感觉总结的已经很到位,特此转载。作者:L...
    WQ_UESTC阅读 11,316评论 4 26
  • { 11、核心动画 需要签协议,但是系统帮签好 一、CABasicAnimation 1、创建基础动画对象 CAB...
    CYC666阅读 5,540评论 2 4
  • 几日的阴霾雨雾终于散去 看着阳光明媚的蓝天 忍不住想高呼:早安!好心情~~ 忽然想起一句话 ——“不忘初心,方得始...
    kiki咕噜阅读 1,360评论 0 1

友情链接更多精彩内容