2012-03-13 43 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