2011-04-18 52 views
4

我動態添加圖像按鈕到一些滾動視圖。他們都指向一個longPressHandler。現在,我怎麼得到哪個按鈕被按下? [發件人標籤]給了我添加到按鈕的longGestureRecognizer標籤,我無法手動設置該標籤。如何通過longPressGestureRecognizer獲取button.tag?

for (...) { 
    UIButton *button = [[UIButton alloc] init]; 
    button.tag = w + h * 3; 
    [button addTarget:self action:@selector(imageButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; 
    UILongPressGestureRecognizer *gest = [[UILongPressGestureRecognizer alloc] 
       initWithTarget:self action:@selector(imageButtonLongPress:)]; 
    gest.minimumPressDuration = 1; 
    gest.delegate = self; 

    [button addGestureRecognizer:gest]; 
    [gest release]; 

    [scrollView addSubview:button]; 
    [button release]; 
} 

- (void) imageButtonLongPress:(id)sender { 
    // how to get button tag here? 
} 

回答

12

有一個在它返回識別器被附連到該視圖的一個UIGestureRecognizer屬性view。我認爲這是你最好的選擇。

- (void) imageButtonLongPress:(id)sender { 
    UIGestureRecognizer *recognizer = (UIGestureRecognizer*) sender; 
    int tag = recognizer.view.tag; 
} 
+0

這是完美的,謝謝你。 – yosh 2011-04-18 09:54:04

+0

這太棒了。謝謝 – 2013-03-09 16:41:27

+0

'recognizer.view.tag'會給我錯誤的標記UIButton clicked。任何解決方案 – 2013-03-20 11:34:29

2

在你的行動,你必須鍵入投下您發送手勢,然後鍵入投其觀點,一個按鈕,然後拿到按鈕的標籤是 -

UILongPressGestureRecognizer *gest = (UILongPressGestureRecognizer *)sender; 
UIButton *button = (UIButton*)[gest view]; 
NSLog(@"%d",[button tag]);