UIScrollView滚动的原因,可以看UIScrollView 原理

我在这里简单的描述一下,UIScrollView的工作原理,当手指touch的时候,UIScrollView会拦截Event,会等待一段时间,在这段时间内,如果没有手指没有移动,当时间结束时,UIScrollView会发送tracking events到子视图上。在时间结束前,手指发生了移动,那么UIScrollView就会进行移动,从而取笑发送tracking。

那么,UIScrollView的子类想要接受touch事件,就是用户点击UIScrollView上的视图时,要先处理视图上的touch,而不发生滚动。这时候就需要UIScrollView的子类重载touchesShouldBegin:withEvent:inContentView: ,从而决定自己是否接受子视图中的touch事件。

上面都是理论的知识,下面看一个简单的例子:

image

外面红色是一个UIScrollView,黄色是在UIScrollView上添加的UIView。最后的效果是,当在黄色区域内touch时,touch事件会作用到UIView上,当touch红色区域时,整个视图上下滚动。下面是实现的过程。

一、创建工程,然后创建myScrollView,并且myScrollView继承自UIScrollView。

#import <UIKit/UIKit.h>

@interface myScrollView : UIScrollView {
}

@end

具体的实现:

#import "myScrollView.h"

#import "MyView.h"

@implementation myScrollView

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setBackgroundColor:[UIColor redColor]];

MyView *myView=[[MyView alloc] initWithFrame:CGRectMake(1, 3, 100, 200)];
[self addSubview:myView];
[myView release];
}
return self;
}

- (void)dealloc
{
[super dealloc];
}

- (BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view
{
NSLog(@"用户点击了scroll上的视图%@,是否开始滚动scroll",view);
//返回yes 是不滚动 scroll 返回no 是滚动scroll
return YES;
}
- (BOOL)touchesShouldCancelInContentView:(UIView *)view
{

NSLog(@"用户点击的视图 %@",view);

//NO scroll不可以滚动 YES scroll可以滚动
return NO;
}
@end

重写了- (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上的视图<MyView: 0x4e26f90; frame = (1 3; 100 200); layer = <CALayer: 0x4e270a0>>,是否开始滚动scroll
2011-06-02 10:19:42.658 scrollTouch[38255:207] 用户点击的视图 <MyView: 0x4e26f90; frame = (1 3; 100 200); layer = <CALayer: 0x4e270a0>>

二、添加mySrollView到根视图上:

- (void)viewDidLoad
{
[super viewDidLoad];

myScrollView *view=[[myScrollView alloc] initWithFrame:CGRectMake(10, 9, 300, 400)];
[view setUserInteractionEnabled:YES];
[view setScrollEnabled:YES];

//NO 发送滚动的通知 但是就算手指移动 scroll也不会动了 YES 发送通知 scroo可以移动
[view setCanCancelContentTouches:YES];
[view setBounces:NO];
// NO 立即通知touchesShouldBegin:withEvent:inContentView 看是否滚动 scroll
[view setDelaysContentTouches:NO];
[view setContentSize:CGSizeMake(300, 900)];
[self.view addSubview:view];
[view release];
}

三、MyView视图的实现。

#import "MyView.h"

@implementation MyView

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setBackgroundColor:[UIColor yellowColor]];
}
return self;
}

- (void)dealloc
{
[super dealloc];
}

@end

from:http://wangjun.easymorse.com/?p=1308