Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1063611
  • 博文数量: 403
  • 博客积分: 10272
  • 博客等级: 上将
  • 技术积分: 4407
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-24 14:22
文章分类

全部博文(403)

文章存档

2012年(403)

分类: 嵌入式

2012-03-30 16:46:29

UIScrollView在开发中是一个非常常用的控件,UIScrollView具有水平、垂直滚动和缩放效果。但是尽然没有响应单击事件这个事件。而这个事件在日常的交互中是非常需要的。比如当用于单击或轻触图片的某个位置时,给于一些交互性提示。

下面我将用例子说明一下如何给UIScrollView添加一个单击的响应。

代码如下:

添加一个自定义的UIScrollView,命名:UITouchScrollView

UITouchScrollView.h代码如下

#import

@protocol UIScrollViewTouchesDelegate
-(void)scrollViewTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event whichView:(id)scrollView;
@end

@interface UITouchScrollView : UIScrollView

@property(nonatomic,assign) id touchesdelegate;

@end

如果要想把单击事件传递出来,那么必须新建一个@Protocol UIScrollViewTouchesDelegate,用于响应并且对事件做出回调。这里说一下IOS的事件委托(Event Delegate)相对C#的事件委托还是不一样的,似乎实现起来没有C#方便。这里就不多说了。

UITouchScrollView.m代码如下

#import "UITouchScrollView.h"


@implementation UITouchScrollView
@synthesize touchesdelegate=_touchesdelegate;
- (void) touchesEnded: (NSSet *) touches withEvent: (UIEvent *) event {

if (!self.dragging) {
//run at ios5 ,no effect;
[self.nextResponder touchesEnded: touches withEvent:event];
if (_touchesdelegate!=nil) {

[_touchesdelegate scrollViewTouchesEnded:touches withEvent:event whichView:self];
}
NSLog(@"UITouchScrollView nextResponder touchesEnded");
}
[super touchesEnded: touches withEvent: event];

}
@end

以上代码只是调用一下自定义的Delegate的方法。但是这里注意一下

[self.nextResponder touchesEnded:touches withEvent:event];这句话的意思是将UIScrollView上的单击事件往下传递,传递到它的父UIView。这样如果父UIView上实现了touchesEnded这个方法,也会响应到。但是这样的写法经过测试在IOS5.0以前的版本可以。但IOS5以后的(包括5)这不能往下传递,这里我也不知道为什么。希望有知道的朋友说一下。

ViewContrller.m代码如下

#pragma mark -

#pragma mark touches event
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(@"view touch began");
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(@"view touch ended");
}
-(void)scrollViewTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event whichView:(id)scrollView{
NSLog(@"scrollView touch ended");

}

功能完成,记得在ViewController.h上加上UIScrollViewTouchesDelegate协议。

另外在说明一下。本来我想用UITapGestureRecognizer来实现的,但是直接引发异常。不明白为什么UITapGestureRecognizer不能注册在UIScrollViews上。

//self.tapGestureRecoginzer=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTaps:)];

//self.tapGestureRecoginzer.numberOfTapsRequired=1;
//self.tapGestureRecoginzer.numberOfTouchesRequired=2;
//[self.view addGestureRecognizer:self.tapGestureRecoginzer];

#pragma mark -
#pragma mark handle taps event
-(void)handleTaps:(UITapGestureRecognizer *)sender{
NSUInteger touchCounter=0;
for (touchCounter=0; sender.numberOfTapsRequired; touchCounter++) {
CGPoint touchPoint=[sender locationOfTouch:touchCounter inView:sender.view];

NSLog(@"touch: %i: %@",touchCounter+1,NSStringFromCGPoint(touchPoint));
}
}
阅读(1631) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~