2012-03-13 35 views
1

我希望能夠削減這些臺詞背下來了口氣:36用循環更改按鈕屬性? Xcode的

[button0 addGestureRecognizer:longPress]; 
[button1 addGestureRecognizer:longPress]; 
[button2 addGestureRecognizer:longPress]; 
[button3 addGestureRecognizer:longPress]; 
[button4 addGestureRecognizer:longPress]; 
[button5 addGestureRecognizer:longPress]; 
[button6 addGestureRecognizer:longPress]; 
[button7 addGestureRecognizer:longPress]; 
[button8 addGestureRecognizer:longPress]; 
[button9 addGestureRecognizer:longPress]; 

等所有的方式!

可能帶有循環?但我不知道如何做到這一點。

謝謝, 關心。

+0

如何按鈕產生的?在界面生成器中還是使用代碼? – sch 2012-03-13 01:09:29

+0

接口生成器 – 2012-03-13 01:12:38

回答

6

您可以爲每個按鈕分配一個標籤,並使用方法viewWithTag通過按鈕循環。

for (int i = 0; i < 36; i++) { 
    UIButton *button = [self.view viewWithTag:i]; 
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; 
    [button addGestureRecognizer:longPress]; 
} 

以下屏幕快照顯示了爲Interface Builder中的每個按鈕分配標記的位置。

enter image description here

如果你有設置IBOutlets的按鈕,你可以使用valueForKey:和無標籤獲得它們:

for (int i = 0; i < 36; i++) { 
    NSString *key = [NSString stringWithFormat:@"button%d", i]; 
    UIButton *button = [self valueForKey:key]; 
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; 
    [button addGestureRecognizer:longPress]; 
} 
+0

感謝一羣人! – 2012-03-13 02:32:17

+0

太棒了,我只是將其添加到我的代碼中,它運行得非常漂亮!使用標籤方法或使用IBOutlets更高效嗎?在運行程序方面,不需要編寫代碼所需的時間。 – 2012-03-13 14:42:23

+0

您選擇的任何一種方法都不會影響應用的性能。 – sch 2012-03-13 15:37:50

2

將你的按鈕放在一個數組中,並使用快速枚舉來遍歷它們。

NSArray *buttons = [NSArray arrayWithObjects:button0, button1, button2, button3, button4, button5, button6, button7, button8, button9, nil]; 

for (UIButton *button in buttons) { 
    [button addGestureRecognizer:longPress]; 
} 
+0

謝謝,我還有一個問題,如果你不介意。你如何用一個手勢識別器工作多個按鈕,因爲當我這樣做時,只有最後一個工作起來 – 2012-03-13 01:14:09

+0

啊,這是一個很好的觀點。您不能將同一個手勢識別器附加到多個視圖。您應該在循環中創建手勢識別器,因此每次迭代都會創建一個新實例。請參閱此答案中的示例:http://stackoverflow.com/a/7883902/663476 – jonkroll 2012-03-13 01:21:58

+0

感謝您的鏈接和幫助! – 2012-03-13 02:32:33