问题
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?
回答1:
If you've got a button that's hooked up to an action in your code, you can change the title without an instance variable.
For example, if the button is set to this action:
-(IBAction)startSomething:(id)sender;
You can simply do this in the method:
-(IBAction)startSomething:(id)sender {
[sender setTitle:@"Hello" forState:UIControlStateNormal];
}
Or if you're wanting to toggle the name of the button, you can create a BOOL
named "buttonToggled" (for example), and toggle the name this way:
-(IBAction)toggleButton:(id)sender {
if (!buttonToggled) {
[sender setTitle:@"Something" forState:UIControlStateNormal];
buttonToggled = YES;
}
else {
[sender setTitle:@"Different" forState:UIControlStateNormal];
buttonToggled = NO;
}
}
回答2:
UIButton *myButton;
[myButton setTitle:@"My Title" forState:UIControlStateNormal];
[myButton setTitle:@"My Selected Title" forState:UIControlStateSelected];
回答3:
Yes. There is a method on UIButton -setTitle:forState:
use that.
回答4:
[myButton setTitle:@"Play" forState:UIControlStateNormal];
回答5:
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];
}
}
回答6:
myapp.h
{
UIButton *myButton;
}
@property (nonatomic,retain)IBoutlet UIButton *myButton;
myapp.m
@synthesize myButton;
-(IBAction)buttonTitle{
[myButton setTitle:@"Play" forState:UIControlStateNormal];
}
回答7:
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];
回答8:
Swift 5 Use button.setTitle()
- If using storyboards, make a IBOutlet reference.
@IBOutlet weak var button: UIButton!
- Call
setTitle
on the button followed by the text and the state.
button.setTitle("Button text here", forState: .normal)
来源:https://stackoverflow.com/questions/5264546/change-button-text-from-xcode