0

I have created 5 buttons using for loop based on incrementing y axis value in CGRectMake. But how can i change the background color of button when i clicked each button?and also title AND having alertview for each button??pls suggest me answer..

//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]; 
}

2 Answers 2

0

Try this

 -(void) buttonClicked:(id) sender
{
  UIButton * button = (UIButton*) sender;
   button.backgroundColor = [UIColor yellowcolor];
   [button setTitle:@"Hello" forState:UIControlStateNormal];
}
0

Set the tag for each button and when it's call buttonclicked: is called, then use it's tag rod decide which background color to set it to::

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;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.