Change button text from Xcode?
I have a IBAction connected to a button in my Interface Build开发者_运维知识库er.
Is it possible to change the text on the button (in IB) from within my code during runtime?
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;
}
}
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.
[myButton setTitle:@"Play" forState:UIControlStateNormal];
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];
}
}
myapp.h
{
UIButton *myButton;
}
@property (nonatomic,retain)IBoutlet UIButton *myButton;
myapp.m
@synthesize myButton;
-(IBAction)buttonTitle{
[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];
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)
精彩评论