Currently I have 14 buttons being created programmatically using a for loop, code below:
int buttonCount = 14;
for (int i=0; i< buttonCount; i++) {
//Create titleString from array object
NSString *stringFromInt = [NSString stringWithFormat:@"%@",[arrayForRound objectAtIndex:i]];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
action:@selector(buttonSelected:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:stringFromInt forState:UIControlStateNormal];
button.titleLabel.font = [UIFont fontWithName:@"helvetica" size:19];
button.tag = i;
[self.view addSubview:button];
}
This works great to create the buttons, I can then populate the Answer Box with the value of the selected button:
-(void)buttonSelected: (UIButton *)sender
{
[_buttonOne setTitle:sender.titleLabel.text forState:UIControlStateNormal];
}
However after the button has been populated I would like to remove it from the screen. If i call button.hidden it simply hides the last button that was programmatically created. I am aware of button.tag and have tried to use this, but it feels like I almost need to do something like:
//Hide button for tag (i know this is incorrect syntax)
button for buttonTag: 3 setHidden;
Is there something similar or a way of doing this?
The button that I am trying to hide is the one that was created programatically. So I want _buttonOne to take on the title of the create button (lets call that letterButton), and then hide letterButton from the view,
UIButton *yourBtn = (UIButton *)[self.button viewWithTag:3];
[yourBtn setHidden:YES];
(code posted by Oh Seung Kwon)
This code work perfectly but it hides the wrong set of buttons. (Hides _buttonOne and not letterButton).
I wonder if it would not be better to create the 12 buttons in nib and name them manually...There will never be more or less that 12.
When your button is tapped, you can set the hidden
property on the action method's sender
argument, which is the button that actually got tapped. This will hide the button which was tapped.
- (void)buttonSelected:(UIButton *)sender {
[_buttonOne setTitle:sender.titleLabel.text forState:UIControlStateNormal];
[sender setHidden:YES];
}
If you meant to retrieve the button with the tag of 3
, you can use this code instead:
[[self.view viewWithTag:3] setHidden:YES];
I don't recommend that you use the tag
property - you should use Interface Builder and an IBOutletCollection
instead.
Like this
UIButton *yourBtn = (UIButton *)[self.view viewWithTag:3];
[yourBtn setHidden:YES];
You could get the view by tag use this message.
[self.view viewWithTag:3];
We always specific tag by macro just like
#define kFirstButtonTag (100)
or use
#define kButtonBeginTag (100)
Then use the macro to get tag.
And in a special number - Case 0, 1 or 2 is always use, begin your tag in a special number could avoid some problems
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With