I Follow the comment and try to fix my problem,but still not working.
when i run the test demo on the simulator,i get this:
and i click the test2, i want to change button title before clear the button title, but i
get this :
i can not clear the button title when click another button.
anyone can help ??
Here is my code
-(void)addbutton
{
for (int i=0; i<3; i++)
{
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake((i*100), 0, 100, 100)];
button.titleLabel.text = @"";
[button setTag:i];
[button setTitle:[self.demoDataArray objectAtIndex:i] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.backgroundColor = [UIColor clearColor];
[button addTarget:self action:@selector(setButtonTitle:) forControlEvents:UIControlEventTouchUpInside];
[self.demoView addSubview:button];
}
}
-(IBAction)setButtonTitle:(id)sender
{
if ([sender tag] == 0)
{
self.demoDataArray = [[NSArray alloc] initWithObjects:@"test5", @"test6", @"test7", @"test8", nil];
[self addbutton];
}
else if([sender tag] == 1)
{
self.demoDataArray = [[NSArray alloc] initWithObjects:@"test9", @"test10", @"test11", @"test12", nil];
[self addbutton];
}
else if([sender tag] == 3)
{
self.demoDataArray = [[NSArray alloc]initWithObjects:@"test13", @"test14", @"test15", @"test16", nil];
[self addbutton];
}
}
Every time any button is pressed, you instantiate new buttons and add them on top of the other ones. You probably want to just update the existing buttons. Try this for your
-addButtonmethod instead:Now the button is instantiated, given a target and action, tagged, and added into the button hierarchy only when it doesn’t already exist. Every time a button is tapped after that, only the titles will be updated.
Also, very important:: in order for
-viewWithTag:to work, you have to use a tag for your buttons that is not equal to 0, the default tag – otherwise the button’s superview will be returned. This means you’ll need to make the following changes in your button handler, which already had a bug with checking the tags (checking against 3 rather than 2). Increment the tags to start at 1 and end with 3 like so:That method could use some cleanup as well to eliminate duplicated code and it’s probably more appropriate to use a
switchstatement here anyways. But that’s neither here nor there.OK, this should probably get you up and running. I didn’t test or compile this so if you do have some problem with the compiler that you’re not able to work through on your own please let me know and I’ll see if I can spot the issue.