0

我使用 for 循环创建了 5 个按钮,基于在CGRectMake. 但是当我单击每个按钮时如何更改按钮的背景颜色?还有标题和每个按钮的警报视图?请建议我回答..

//array taken for button titles
NSArray *array1=[NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil];

int k=0;  

for(int i=50;i<=350;i=i+70)
{
  button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
  button.frame=CGRectMake(30,i,35,40);
  [button addTarget:self action:@selector(buttonclicked:) forControlEvents:UIControlEventTouchUpInside];
  if (k<[array1 count])
  {
    [button setTitle:[array1 objectAtIndex:k] forState:UIControlStateNormal];
  }
  k++;  
  [self.view addSubview:button]; 
}
4

2 回答 2

0

尝试这个

 -(void) buttonClicked:(id) sender
{
  UIButton * button = (UIButton*) sender;
   button.backgroundColor = [UIColor yellowcolor];
   [button setTitle:@"Hello" forState:UIControlStateNormal];
}
于 2012-08-01T05:29:03.400 回答
0

为每个按钮设置tag,当它被调用时 buttonclicked: 被调用,然后使用它的tag棒决定将它设置为的背景颜色::

int temptag;
temptag = 0;
for(int i=50;i<=350;i=i+70)
{
  button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
  button.frame=CGRectMake(30,i,35,40);
  [button addTarget:self action:@selector(buttonclicked:)  forControlEvents:UIControlEventTouchUpInside];
  button.tag = temptag;
  if (k<[array1 count])
  {
    [button setTitle:[array1 objectAtIndex:k] forState:UIControlStateNormal];
  }
  k++;  
  temptag++;
  [self.view addSubview:button]; 
}


-(void)buttonclicked:(id)sender
{
  UIButton *btn = (UIButton *)sender;
  switch (btn.tag) {
    case 0:
      btn.backgroundColor = [UIColor redColor];
      break;
    case 1:
      btn.backgroundColor = [UIColor grayColor];
      break;
    case ...:
      ....
    default:
      break;
    }
}
于 2012-08-01T05:31:51.327 回答