2014-06-18 105 views
0

我正在開展掃雷遊戲,我想在用戶長時間點擊遊戲板的圖塊時添加標誌。 我實現了這個代碼:UIButton上的長按手勢識別器?

對於每一個按鈕,在遊戲鍵盤:

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressTap:)]; 
      longPress.minimumPressDuration = 1.0f; 
      [self.button addGestureRecognizer:longPress]; 

在自我的方法longPressTap:

- (void)longPressTap:(Tile *)sender { 
     if (sender.block.marking == MARKING_FLAGGED) { 
      // if already a flag I mark as a blank tile, with color defined for gameboard 
      sender.backgroundColor = UIColorFromRGB(0x067AB5); 
      sender.block.marking = MARKING_BLANK; 
      self.flagCount++; 
     } 
     else{ 
      // if it's not a flag I mark as a flag and set the flag image for the tile 
      [sender setBackgroundImage:[UIImage imageNamed:IMAGE_NAME_FLAG] forState:UIControlStateNormal]; 
      sender.block.marking = MARKING_FLAGGED; 
      self.flagCount--; 
     } 
} 

當然自我的,是我的UIGestureRecognizerDelegate 。 但是當我嘗試長按上一瓦,應用程序崩潰,給這個錯誤:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UILongPressGestureRecognizer block]: unrecognized selector sent to instance 0x8cf2b00' 

我該怎麼辦?我剛剛開始使用Obj-C編程,所以如果有人可以幫我解釋我做錯了什麼,我會非常感激。

回答

0

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UILongPressGestureRecognizer block]: unrecognized selector sent to instance 0x8cf2b00'

從這個錯誤是非常明顯的應用是因爲[UILongPressGestureRecognizer block]崩潰。 UILongPressGestureRecognizer沒有名爲block的方法,所以它正在崩潰。

- (void)longPressTap:(Tile *)sender { 
} 

正如你在這個方法的實現sender預期不Tile對象,它實際上是UILongPressGestureRecognizer

預期的方法是

- (void)longPressTap:(UILongPressGestureRecognizer *)sender 
{ 
} 
+0

是啊,這就是我的想法是錯的,但經過UILongPressGestureRecognizer作爲參數longPressTap: 我怎麼能檢查哪些瓷磚用戶選擇並將其標記爲標誌/空白?對不起noob問題,但我想了解 –

+0

使用'[發送者位置查看]'從那裏找到觸摸的位置,你應該有一個邏輯來獲得相關的'瓦片' –

+0

嘗試'[發送者視圖]'也可能工作 –

0

我明白你的問題。我現在可以參數中的「瓷磚」是什麼?

- (void)longPressTap:(Tile *)sender 

使用,這可能是有益的

- (void)longPressTap:(UILongPressGestureRecognizer *)sender 

,不要使用直接的瓷磚。用瓷磚對象直接在這裏,使這個全局對象..

+0

我傳遞Tile作爲參數,因爲我不知道如何識別用戶選擇的Tile。所以現在我有: - (無效)longPressTap:(UILongPressGestureRecognizer *)發件人 但你能給我一個片段標記爲標誌瓷磚/空白? ty –

+0

嘗試向Tile對象添加長按手勢而不是按鈕,並使用Tile對象作爲發件人參數,它可能會工作 – Viper

2
- (void)showOptions:(UILongPressGestureRecognizer*)sender{ 

UIButton *btn = (UIButton*)sender.view; 
NSLog(@"view tag %d",sender.view.tag); 

if (sender.state == UIGestureRecognizerStateEnded) 
{ 

} 
else if (sender.state == UIGestureRecognizerStateBegan) 
{ 
    [self.bubbleDelegate showOptionsForMessage:btn]; 
} 

}

+0

偉大的解決方案!這解決了UILongPressGestureRecognizer在內部觸摸時再次觸發的問題。 –