在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 *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanFrom:)]; [self.view addGestureRecognizer:panRecognizer]; panRecognizer.maximumNumberOfTouches = 1; panRecognizer.delegate = self; [panRecognizer release];
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch { }里面可以先filter event,决定要不要丢给一开始assign给panRecognizer的selector function
- (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); } }