监视来自非视图控制器类的手势

时间:2012-03-20 11:56:19

标签: objective-c class getter-setter

我想监视来自外部类的向上,向下,向左或向右滑动手势(即,方法不在我的视图控制器中)。我已经设法使用外部类和属性来设置它来判断推送的方向,但我现在想要在检测到滑动时在视图控制器内运行一个方法(它将接受滑动的方向,并且相应的行为)。

我不确定当在另一个类中检测到滑动时,如何让一个类中的方法运行。目前,我的SwipeDetector类的设置如下所示,我希望将这些kDirectionKey常量提供给视图控制器类中的方法,并且只要进行滑动,该方法就会触发。这是我应该使用观察员的东西吗?我以前从未使用它们,看起来有点令人生畏。

@synthesize up = _up;
@synthesize down = _down;
@synthesize left = _left;
@synthesize right = _right;

@synthesize swipedDirection = _swipedDirection;

- (void)recogniseDirectionSwipes
{
    _up = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(upSwipeDetected)];
    _down = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(downSwipeDetected)];
    _left = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(leftSwipeDetected)];
    _right = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightSwipeDetected)];

    _up.direction = UISwipeGestureRecognizerDirectionUp;
    _down.direction = UISwipeGestureRecognizerDirectionDown;
    _left.direction = UISwipeGestureRecognizerDirectionLeft;
    _right.direction = UISwipeGestureRecognizerDirectionRight;

}

- (void)upSwipeDetected
{
    NSLog(@"Direction swipe sniffed out, and that direction was up!");
    _swipedDirection = kDirectionKeyUp;
}

- (void)downSwipeDetected
{
    NSLog(@"Direction swipe sniffed out, and that direction was down!");
    _swipedDirection = kDirectionKeyDown;
}

- (void)leftSwipeDetected
{
    NSLog(@"Direction swipe sniffed out, and that direction was left!");
    _swipedDirection = kDirectionKeyLeft;
}

- (void)rightSwipeDetected
{
    NSLog(@"Direction swipe sniffed out, and that direction was right!");
    _swipedDirection = kDirectionKeyRight;
}

@end

1 个答案:

答案 0 :(得分:1)

如果您在UIView上进行复杂的手势检测,那么在UIViewController的视图中执行此操作是有意义的。要封装该功能,您需要创建一个UIView子类,在那里实现您的手势处理,然后根据需要将适当的消息传递回控制器类。

后者似乎是你的主要问题。这是delegation pattern的经典案例。如果您选择创建自定义UIView来实现手势处理,那么我们将其称为FooView,然后您可以创建正式协议FooViewDelegate来处理到视图委托的消息。在这种情况下,委托将是您的控制器类。关于协议的Apple docs

或者,您可以在UIViewController子类中实现手势检测,而不必担心委派。这取决于您的要求。

作为另一种选择(您提到的那个),如果视图控制器保留对SwipeDetector类的引用,您可以观察SwipeDetector实例上的属性。

[self addObserver:self forKeyPath:@"swipeDetector.swipeDirection" 
          options:NSKeyValueObservingOptionNew 
          context:NULL];

请注意,要使KVO正常工作,您需要使用SwipeDetector课程中的属性访问者,例如self.swipeDirection = kDirectionKeyUp;而不是直接设置ivars。