ios - 在 iOS 中添加 UIButtons 数组

标签 ios objective-c uibutton

我想使用 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/

相关文章:

ios - UITableViewCell:iPhone 6上复选标记旁边右侧的垂直线

ios - 如何在 Swift 中更改按钮标题的颜色

ios - 在 Rx Swift 中自动将 UITableView 滚动到底部

iOS -> 非消耗性应用内购买实际上可以包含代码吗?

ios - 从 UTC 字符串获取日期

ios - 我可以序列化持有授权 Twitter 帐户的 ACAccount 对象吗?

ios - 在UIButton上添加“点击”效果

ios - 自定义 UIButton 抛出多个设计错误

ios - objective-c 串联键

ios - 构建基本应用程序 iOS 应用程序 - 单一 View - 最佳实践