UIScrollView的作用原理,实现scrollView中touch事件作用子视图分类:IOS 发布时间:2012/5/7 1:09:52
我们知道当多个视图进行叠加的时候,touch事件是作用到最上面的视图上,但是如果父视图是UIScrollView,如果默认,可能touch子视图会造成UIScrollView的滚动。 UIScrollView滚动的原因,可以看UIScrollView 原理。 我在这里简单的描述一下,UIScrollView的工作原理,当手指touch的时候,UIScrollView会拦截Event,会等待一段时间,在这段时间内,如果没有手指没有移动,当时间结束时,UIScrollView会发送tracking events到子视图上。在时间结束前,手指发生了移动,那么UIScrollView就会进行移动,从而取笑发送tracking。 那么,UIScrollView的子类想要接受touch事件,就是用户点击UIScrollView上的视图时,要先处理视图上的touch,而不发生滚动。这时候就需要UIScrollView的子类重载touchesShouldBegin:withEvent:inContentView: ,从而决定自己是否接受子视图中的touch事件。 上面都是理论的知识,下面看一个简单的例子: 外面红色是一个UIScrollView,黄色是在UIScrollView上添加的UIView。最后的效果是,当在黄色区域内touch时,touch事件会作用到UIView上,当touch红色区域时,整个视图上下滚动。下面是实现的过程。 一、创建工程,然后创建myScrollView,并且myScrollView继承自UIScrollView。 #import @interface myScrollView : UIScrollView { @end 具体的实现: #import “myScrollView.h” #import “MyView.h” @implementation myScrollView - (id)initWithFrame:(CGRect)frame MyView *myView=[[MyView alloc] initWithFrame:CGRectMake(1, 3, 100, 200)]; - (void)dealloc - (BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view NSLog(@”用户点击的视图 %@”,view); //NO scroll不可以滚动 YES scroll可以滚动 重写了- (BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view方法和- (BOOL)touchesShouldCancelInContentView:(UIView *)view方法。 其中(BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view,是用户点击黄色区域内,先触发这个方法,当返回YES时,touch事件作用到黄色视图上,当返回no时,红色可以上下滚动。 (BOOL)touchesShouldCancelInContentView:(UIView *)view是发送tracking前,先作用这个方法。 下面是点击黄的区域的日志: 2011-06-02 10:19:42.469 scrollTouch[38255:207] 用户点击了scroll上的视图 二、添加mySrollView到根视图上: - (void)viewDidLoad myScrollView *view=[[myScrollView alloc] initWithFrame:CGRectMake(10, 9, 300, 400)]; //NO 发送滚动的通知 但是就算手指移动 scroll也不会动了 YES 发送通知 scroo可以移动 三、MyView视图的实现。 #import “MyView.h” @implementation MyView - (id)initWithFrame:(CGRect)frame - (void)dealloc @end http://www.alexc.me/uiscrollview-and-uidatepicker/153/ @interface PickerAwareUIScrollView : UIScrollView { - (BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view { - (BOOL)touchesShouldCancelInContentView:(UIView *)view { |
|


最新评论