我想使用 for 循环添加 UIButton
。每个按钮都会有不同的操作。
我的代码是:
NSArray *methods = [[NSArray alloc]initWithObjects:@"1",@"2", @"3", @"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15", nil];
int x=0;
for (int t=0;t<=14;t++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector([methods[t]]) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"" forState:UIControlStateNormal];
button.frame = CGRectMake(275, x+8, 28, 16);
[button setBackgroundColor:[UIColor colorWithRed: 10.0/255.0f green:100.0/255.0f blue:150.0/255.0f alpha:1.0f]];
button.layer.cornerRadius = 10;
[button setBackgroundImage:[UIImage imageNamed:@"Plus"] forState:UIControlStateNormal];
[segmentedView1 addSubview:button];
[self.view addSubview:segmentedView1];
x+=20;
}
遇到错误:
[button addTarget:self action:@selector([methods[t]]) 行中的“预期标识符”
此外,我如何为以编程方式添加的此类按钮制作 socket ?
有什么解决办法吗? 谢谢
最佳答案
我建议为所有按钮分配相同的选择器。指向按钮的指针将发送到此选择器,您可以使用 .tag
属性识别按下了哪个按钮。
for (int t=0;t<=14;t++) {
...
[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
}
- (void)buttonPressed:(id)sender {
if (((UIButton *)sender).tag == 1) {
...
}
...
}
同时将 [self.view addSubview:segmentedView1];
移出循环。
关于ios - 在 iOS 中添加 UIButtons 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26362327/