在不同的IBAction中更改以编程方式创建的UIButton的属性

时间:2014-06-03 07:16:59

标签: ios uibutton

我有一种方法可以编程方式创建多个UIButton个实例,并将它们放在视图中。另一个IBAction需要在触发时更改其中一个UIButton的背景颜色,但是当我尝试操作它时,它会告诉我在UIView *类型的对象上找不到该属性

按钮使用以下方式创建:

UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
[view addSubview:button];

当我尝试从其他IBAction访问它时,如:

button.backgroundColor = [UIColor blackColor];

由于上述错误而失败。

非常感谢任何帮助。我看到另一个答案建议将数组创建为IBOutlet并以这种方式访问​​它,但我想知道是否有另一种方式。

谢谢!

2 个答案:

答案 0 :(得分:1)

全局声明此button并识别tag中的每个按钮,就像或假设这样

 UIButton * button, *button2; // declare in your view controller.h

 - (IBAction)butaction:(id)sender;    //this is your color change method;

在你的视图controller.m中,只要你添加这个按钮

 button = [UIButton buttonWithType:UIButtonTypeCustom];
 button.tag=10;   //this is important
 [self.view addSubview:button];

  button1 = [UIButton buttonWithType:UIButtonTypeCustom];
  button1.tag=20;   //this is important
 [self.view addSubview:button1];


  //here ur color change method

     - (IBAction) butaction:(UIButton*)sender {


     switch (sender.tag)
      {
       case 10:
         [button setBackgroundColor:[UIColor blackColor]];

       break;

        case 20:
            [button1 setBackgroundColor:[UIColor blackColor]];
          break;

       default:
        break;

           }
        }

答案 1 :(得分:1)

试试这个,这可能会有所帮助

for (int index=1; index<=5; index++) {
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self action:@selector(ButtonClickedFunction:) forControlEvents:UIControlEventTouchUpInside];
    button.tag= index;
    [view addSubview:button];
};

在IBAction中实现这个

 -(IBAction)ButtonClickedFunction:(UIButton *)button{
    button.backgroundColor = [UIColor blackColor];
  }

注意:在这里我创建了5个按钮但没有设置框架。请根据您的要求设置框架。 感谢

相关问题