2012-08-12 83 views
1

我想添加一個手勢識別器到我的按鈕,以便我可以運行代碼,如果用戶刷過按鈕框架。如果滑動按鈕向上,向右,向左或向下,我還希望此代碼有所不同。如何初始化UIGestureRecognizer?

-(void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    button.frame=CGRectMake(0, 0, 100, 100); 
    [self.view addSubview:button]; 
    UIGestureRecognizer *swipe=[[UIGestureRecognizer alloc]initWithTarget:button action:@selector(detectSwipe)]; 
    [button addGestureRecognizer:swipe]; 
} 

那麼,我做了initWithTarget:action:的事情是否正確?現在,我這樣做,我如何實施detectSwipe方法?

這是我對如何實施detectSwipe

  -(IBAction)detectSwipe:(UIButton *)sender 
     { 
     /* I dont know how to put this in code but i would need something like, 
if (the swipe direction is forward and the swipe is > sender.frame){ 
[self ForwardSwipeMethod]; 
    } else if //same thing for right 
    else if //same thing for left 
    else if //same thing for down 

     } 
+0

detectSwipe:沒有得到按鈕發件人。它是作爲參數傳入的手勢識別器 - 或者您還會如何知道識別器檢測到哪個手勢? – 2012-08-12 20:51:22

回答

2

你可能想使用UISwipeGestureRecognizer是。 UIGestureRecognizer通常不應該被使用,除非你繼承它。你的代碼應該與下面類似。

UISwipeGestureRecognizer *swipe=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(detectSwipe)]; 
swipe.direction = UISwipeGestureRecognizerDirectionRight; 
[button addGestureRecognizer:swipe]; 
2

你有不同的手勢識別器的目標的所有正確的想法。目標是接收給定選擇器消息的對象,因此您的initWithTarget:調用應接受self作爲參數,除非您在按鈕的子類中實現detectSwipe方法。

+0

不完全正確。請參閱我答案中的其他要點。 – 2012-08-12 20:52:09

5

不,這是不正確的。手勢識別器的目標不是按鈕,它是檢測手勢時調用動作方法的對象(否則它如何知道哪個對象調用該方法?在OO中,方法調用/消息發送需要顯式方法名稱一個實例或類)。

所以,你很可能想

recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipe:)]; 

您還沒有創建UIGestureRecognizer直接的實例,但是一個如果它的具體子類,UISwipeGestureRecognizer在這種情況下。

後的alloc-initting識別器,將其附加到要被認可的觀點:

[button addGestureRecognizer:recognizer]; 

然後在didSwipe:方法,您可以使用手勢識別的屬性來決定什麼大小/距離/其他屬性的刷卡是。

You better read some docs next time.

1

H2CO3的答案是完整的。只要不要忘記你在選擇器的末尾丟失了冒號「:」!它應該是這樣的:@selector(detectSwipe:)

冒號「:」是因爲你的方法有一個說法:(UIButton *)sender