2009-10-23 83 views
0

我在for循环中动态创建了五个按钮。现在我想将一个OnClick事件与执行不同操作的每个按钮关联起来。我如何做到这一点,以及如何检测哪个按钮被点击?iPhone中的多个按钮onclick事件中的问题

for (NSUInteger i=0;i<5;i++) 
{ 
    UIButton *myButton1 = [[UIButton buttonWithType:UIButtonTypeCustom] 
     initWithFrame:CGRectMake(5, 57,15, 15)]; 
    [myButton1 setTitle:@"Click Me!" forState:UIControlStateNormal]; 
    [myButton1 addTarget:self action:@selector(buttonClicked1:) 
     forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:myButton1]; 
} 

回答

2

你可以asseble选择名称到一个字符串,把串入一个选择:

for (int i=0; i<5; i++) 
{ 
    NSString *actionName = [NSString stringWithFormat:@"buttonClicked%i", i]; 
    SEL action = NSSelectorFromString(actionName); 
    // … 
} 

但随着按钮可能会做同样的事情,它会更好,如果他们都被称为同样的方法,在那里你会直接告诉按钮分开由tag

for (int i=0; i<5; i++) 
{ 
    // … 
    [button setTag:i]; 
    [button addTarget:self action:@selector(buttonClicked:) 
     forControlEvents:UIControlEventTouchUpInside]; 
} 

- (void) buttonClicked: (id) button 
{ 
    const int tag = [button tag]; 
    switch (tag) { /* … */ } 
} 

顺便说一句,为什么很多人坚持写NSInteger当你只需输入int?有区别吗?没有我知道的。

+0

FWIW:“构建32位应用程序时,NSInteger是一个32位整数,64位应用程序将NSInteger视为一个64位整数。” http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/doc/uid/20000018-DontLinkElementID_8 – 2009-10-23 09:26:57

+0

阿哈,有甚至一个关于他们的SO线程:http://stackoverflow.com/questions/13725。 – zoul 2009-10-23 09:57:16

0

为什么在for循环中创建5个按钮? 为什么你不使用Interface Builder有什么特别的原因吗?

此外,您发布的代码会将每个按钮置于相同的位置。一个按钮将位于上一个按钮的顶部,依此类推。