2012-03-20 96 views
0

我想監視上,下,左,右滑動手勢從外部類(即與方法不在我的視圖控制器中)。我已經設法使用外部類和屬性來判斷哪個方向被推動,但我現在想要在檢測到滑動時在視圖控制器內運行一個方法(它將接受哪個方向被滑動,並且按指示行動)。從非視圖控制器類監視手勢

我不確定如何讓一個類中的方法在另一個類型中檢測到滑動時運行。目前,我的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

如果你在一個UIView做複雜的手勢檢測,這將是有意義的做,在UIViewController的觀點。爲了封裝這個功能,你需要創建一個UIView子類,在那裏實現你的手勢處理,然後根據需要將適當的消息傳遞迴控制器類。

後者似乎是你的主要問題。這是delegation pattern的經典案例。如果您選擇創建自定義UIView來實現手勢處理,我們將其稱爲FooView,然後您可以創建一個正式協議FooViewDelegate來處理向視圖委託的消息。在這種情況下,代表將是您的控制器類。協議上的Apple docs

或者,您可以在UIViewController子類中實現手勢檢測,而不必擔心委派。這取決於你的要求。

作爲另一種替代方法(您提到的另一種方法),如果視圖控制器保留對類的引用,則可以觀察SwipeDetector實例上的屬性。

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

注意,對於志願工作,你需要用你的SwipeDetector類,如屬性訪問self.swipeDirection = kDirectionKeyUp;而不是直接設置ivars。

相關問題