0

我已经使用循环创建了按钮并设置了属性并合成了按钮。现在我想更改另一个视图控制器中的按钮颜色。I am setting the tag values for each button and i can get the tag values properly in another view controller, when select the buttons. 现在我想更改每个按钮的背景颜色。

这是示例代码,

在 CustomView.h

    UIButton *customBtn;
    property (nonatomic, strong) UIButton *customBtn;
    @synthesize customBtn;

在 CustomView.m 中

for (int i=0; i<=[resultArray count]; i++)
{
     customBtn= [UIButton buttonWithType:UIButtonTypeCustom];
     customBtn = CGRectMake(X, 30, 20, 20); notsupport = [[UILabel alloc]initWithFrame:CGRectMake(25, 30, 290, 20)];
     [customBtn addTarget:customDelegate actionselector(MyAction:) forControlEvents:UIControlEventTouchUpInside];
     [self.view addSubview:customBtn];
     X = X + 30;

}

在视图控制器中:

            viewController.customBtn.backgroundColor = [UIColor blackColor];

它确实会影响所有按钮的背景颜色,所以我如何更改每个按钮的背景颜色。如果我为所有按钮创建单独的实例,我可以更改按钮的背景颜色。使用按钮的单个实例,我们如何更改按钮背景的颜色。

请帮帮我。

谢谢!

4

5 回答 5

2
for (int i=0; i<=[resultArray count]; i++)
{
    customBtn= [UIButton buttonWithType:UIButtonTypeCustom];
    customBtn = CGRectMake(X, 30, 20, 20); notsupport = [[UILabel alloc]initWithFrame:CGRectMake(25, 30, 290, 20)];
    [customBtn addTarget:customDelegate actionselector(MyAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:customBtn];
    X = X + 30;
    customBtn.tag = i;

   [buttonAry addObject:customBtn];



}

到循环结束时,您将有 n 个按钮buttonAry,每个按钮都有唯一的标签。

您可以在另一个类中读取该数组

 for (int i=0; i<=[buttonAry count]; i++)
{
   UIButton *button = [buttonAry objectAtIndex:i];

   UIColor *color =  [colorAry objectAtIndex:i];


  button.backgroundColor = [UIColor color];


}

colorAry你可以有不同的颜色

于 2012-12-28T07:47:52.220 回答
0

要么你可以用viewWithTag.

或者,您可以创建一个数组IBOutlets,然后您的工作就完成了。

于 2012-12-28T07:36:42.337 回答
0
for (int i=0; i<=[resultArray count]; i++)
{
   customBtn= [UIButton buttonWithType:UIButtonTypeCustom];
   customBtn = CGRectMake(X, 30, 20, 20); notsupport = [[UILabel alloc]initWithFrame:CGRectMake(25, 30, 290, 20)];
  [customBtn addTarget:customDelegate actionselector(MyAction:) forControlEvents:UIControlEventTouchUpInside];

  customBtn.tag = i;

  [self.view addSubview:customBtn];
  X = X + 30;

}

-(IBAction)MyAction:(id)sender{

  UIButton *btn = (UIButton *)sender;

  NSLog:(@"tag:%d"btn.tag);
  // here you find your specific button, 
}
于 2012-12-28T07:43:06.640 回答
0

使用viewWithTag方法。例如

UIButton *button = (UIButton *)[viewController.view viewWithTag:aTag];

于 2012-12-28T07:33:04.223 回答
0

要么遵循 Anoop Vaidya,要么使用 NSNotification 将您的按钮对象发送到另一个类,它将保存您按钮的所有属性。

于 2012-12-28T07:39:37.043 回答