如何用UIGestureRecognizer去侦测使用者输入


在3.2以前我们要用到UITouch跟用户互动,大部分都是通过UIResponser四种methods

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event

有些人会把UITouch重新wrap丢到自己的queue里面去处理,
不然就是直接在这几个function里直接判断,其实都不会差太多,简单的说...就是麻烦 
3.2以后,透过UIGestureRecognizer及其它继承它的UIxxxGestureRecognizer,
侦测使用者输入就变的简单许多

UILongPressGestureRecognizer
UIPanGestureRecognizer
UIPinchGestureRecognizer
UIRotationGestureRecognizer
UISwipeGestureRecognizer
UITapGestureRecognizer

照名字看大概就知道这是做什么用的,所以我就不解释啦,直接看用法.....
以UIPanGestureRecognizer为例,这是处理使用者用一只手指(或多只)在屏幕上滑来滑去的动作,
要侦测这个动作,只要加下面这段code进viewDidLoad或任何你需要的地方...

UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanFrom:)];
[self.view addGestureRecognizer:panRecognizer];
panRecognizer.maximumNumberOfTouches = 1;
panRecognizer.delegate = self;
[panRecognizer release];

第一个很简单,就是确定要给这个recognizer handle的event,就会去call这个class底下的handlePanFrom:
然后把recognizer加进UIView里(addGestureRecognizer),
因为同时间我只想知道一只手指的动作,所以我用maximumNumberOfTouches=1来限制,
当然,你可以改变maximumNumberOfTouches跟minimumNumberOfTouches的值来当成filter,接着把delegate设定成自己(记得header要加上UIGestureRecognizerDelegate),不过这样还没有结束...
我们要补上这个delegate method

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
}
里面可以先filter event,决定要不要丢给一开始assign给panRecognizer的selector function
譬如我只想要看某个subview的事件

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
   UIView *aview = [self.view viewWithTag:1000];
   if (touch.view != aview) {
     return NO; // 不理這個event
   }
   return YES;
}

接下来就是

- (void)handlePanFrom:(UIPanGestureRecognizer *)recognizer {        
        //拿到手指目前的位置
        CGPoint location = [recognizer locationInView:self.view];
        UIView *aview = [self.view viewWithTag:1000];

        // 如果UIGestureRecognizerStateEnded的話...你是拿不到location的
        // 不判斷的話,底下改frame會讓這個subview消失,因為origin的x和y就不見了!!!
        if(recognizer.state != UIGestureRecognizerStateEnded)
        {
                aview.frame = CGRectMake(location.x, location.y, aview.frame.size.width, aview.frame.size.height);
        }
}

不同的UIGestureRecognizer subclass都会有不同特点,譬如说Pinch的scale,velocity和Swipe的direction,
直接简化了处理UITouch的步骤,大家只要知道这些特点,处理使用者输入就会得心应手啦~
遇到灵异事件...记得先看看有没有判断UIGestureRecognizer的state

你可能感兴趣的:(function,filter,header,velocity,action,UIView)