I have a IBAction connected to a button in my Interface Builder.
Is it possible to change the text on the button (in IB) from within my code during runtime?
This question is related to
iphone
objective-c
xcode
interface-builder
[myButton setTitle:@"Play" forState:UIControlStateNormal];
There is no need to add if{}else{} control flow. Initialise the button texts for different states at the View or ViewController constructor:
[btnCheckButton setTitle:@"Normal" forState:UIControlStateNormal]; [btnCheckButton setTitle:@"Selected" forState:UIControlStateSelected];
Then switch the button state to Selected:
[btnCheckButton setSelected:YES];
Then switch the button state to Normal:
[btnCheckButton setSelected:NO];
myapp.h
{
UIButton *myButton;
}
@property (nonatomic,retain)IBoutlet UIButton *myButton;
myapp.m
@synthesize myButton;
-(IBAction)buttonTitle{
[myButton setTitle:@"Play" forState:UIControlStateNormal];
}
UIButton *myButton;
[myButton setTitle:@"My Title" forState:UIControlStateNormal];
[myButton setTitle:@"My Selected Title" forState:UIControlStateSelected];
Yes. There is a method on UIButton -setTitle:forState:
use that.
Another way to toggle:
- (IBAction)signOnClick:(id)sender
{
if ([_signOnButton.titleLabel.text isEqualToString:@"Sign off"])
{
[sender setTitle:@"Sign on" forState:UIControlStateNormal];
}
else
{
[sender setTitle:@"Sign off" forState:UIControlStateNormal];
}
}
Swift 5 Use button.setTitle()
@IBOutlet weak var button: UIButton!
setTitle
on the button followed by the text and the state.button.setTitle("Button text here", forState: .normal)
Source: Stackoverflow.com