在我之前的评论中,我不清楚您为什么要进行子类化,但您澄清了这是因为您有多个手势处理程序正在进行。很好。
因此,这里有一些自定义平移手势的示例代码,HorizontalPanGestureRecognizer,仅当第一个移动是水平的时才会触发:
// HorizontalPanGestureRecognizer.h
#import <UIKit/UIKit.h>
@interface HorizontalPanGestureRecognizer : UIPanGestureRecognizer
@end
和
// HorizontalPanGestureRecognizer.m
#import "HorizontalPanGestureRecognizer.h"
#import <UIKit/UIGestureRecognizerSubclass.h>
@interface HorizontalPanGestureRecognizer ()
{
BOOL _hasConfirmedDirection;
BOOL _wasHorizontal;
CGPoint _origLoc;
}
@end
@implementation HorizontalPanGestureRecognizer
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];
UITouch *touch = [touches anyObject];
_hasConfirmedDirection = NO;
_origLoc = [touch locationInView:self.view];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesMoved:touches withEvent:event];
if (self.state == UIGestureRecognizerStateFailed) return;
if (!_hasConfirmedDirection)
{
CGPoint translation = [self translationInView:self.view];
_hasConfirmedDirection = YES;
_wasHorizontal = (fabs(translation.x) > fabs(translation.y));
}
if (!_wasHorizontal)
self.state = UIGestureRecognizerStateFailed;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesEnded:touches withEvent:event];
if (!_wasHorizontal)
self.state = UIGestureRecognizerStateFailed;
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesCancelled:touches withEvent:event];
if (!_wasHorizontal)
self.state = UIGestureRecognizerStateFailed;
}
- (CGPoint)locationInView:(UIView *)view
{
CGPoint superLocation = [super locationInView:view];
if (_hasConfirmedDirection)
superLocation.y = _origLoc.y;
return superLocation;
}
- (CGPoint)translationInView:(UIView *)view
{
CGPoint superTranslation = [super translationInView:view];
if (_hasConfirmedDirection)
superTranslation.y = 0.0f;
return superTranslation;
}
@end
然后你可以让你的主视图控制器中的处理程序适当地使用它(在这个例子中,只是拖动一个 UILabel )。在 viewDidLoad 中,创建手势:
HorizontalPanGestureRecognizer *recognizer = [[HorizontalPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleCustomPan:)];
[self.view addGestureRecognizer:recognizer];
然后处理程序看起来像:
- (void)handleCustomPan:(UIPanGestureRecognizer *)sender
{
switch (sender.state) {
case UIGestureRecognizerStateChanged:
if (!_panLabel)
{
// In my case I'm creating a UILabel to drag around, whereas you might just drag
// whatever countrol you want to drag.
//
// But, regardless, I'm keeping track of the original center in _panLabelOrigCenter
[self makePanLabel:sender];
}
CGPoint translate = [sender translationInView:self.view];
_panLabel.center = CGPointMake(_panLabelOrigCenter.x + translate.x, _panLabelOrigCenter.y + translate.y);
break;
case UIGestureRecognizerStateEnded:
[self removePanLabel];
break;
default:
break;
}
}
(显然,这是 ARC 代码。如果不是 ARC,请添加必要的附加代码行以进行例行内存管理。)