UIScrollView在开发中是一个非常常用的控件,UIScrollView具有水平、垂直滚动和缩放效果。但是尽然没有响应单击事件这个事件。而这个事件在日常的交互中是非常需要的。比如当用于单击或轻触图片的某个位置时,给于一些交互性提示。
下面我将用例子说明一下如何给UIScrollView添加一个单击的响应。
代码如下:
添加一个自定义的UIScrollView,命名:UITouchScrollView
UITouchScrollView.h代码如下
@protocol UIScrollViewTouchesDelegate
-( void)scrollViewTouchesEnded:(NSSet *)touches withEvent:(UIEvent *) event whichView:( id)scrollView;
@end
@interface UITouchScrollView : UIScrollView
@property(nonatomic,assign) id<UIScrollViewTouchesDelegate> 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 -
-( 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.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));
}
}