I want a UIButton when tapped to change its title to "Restart" and when tapped again to change its title to "Stop". This code I have changes the Button title to "Restart" but when I tap on the button again nothing happens.
-(IBAction)restartPressed{
if (self.restart){
[self.restart setTitle:"@Restart" forState:UIControlStateNormal];
else {
[self.restart setTitle:"@Stop" forState:UIControlStateSelected];
}
}
You need to set both times the state for UIControlStateNormal
. UIControlStateSelected
is a state, what is barley visible.
Declare a variable, what you update every time the button is being pressed.
@property (nonatomic, assign) BOOL isRestart;
Than set the title for the right state observing the above declared value.
- (IBAction) restartPressed {
self.isRestart = !self.isRestart;
if (self.isRestart){
[self.restart setTitle:@"Restart" forState:UIControlStateNormal];
} else {
[self.restart setTitle:@"Stop" forState:UIControlStateNormal];
}
}
Also, make sure the restartPressed
function is called.
You can take a global boolean variable:
var isButtonClicked = false
@IBAction func restartClicked(_ sender: AnyObject) {
isButtonClicked = !isButtonClicked
restartButton.setTitle(isButtonClicked ? "Stop" : "Restart", for: .normal)
}
The code is in swift. You can convert it to objective C
Declare int i and int rem globally:
@interface ViewController ()
{
int i;
int rem;
}
Then in your restart button Action add the below code:
- (IBAction)restartPressed:(id)sender
{
if((rem = i % 2 == 0))
{
[_restartBtn setTitle:@"restart" forState:UIControlStateNormal];
i=i+1;
}
else
{
[_restartBtn setTitle:@"stop" forState:UIControlStateNormal];
i=i+1;
}
}
Hope this helps !
Try this :
In ViewDidLoad
[btn setTitle:@"Restart" forState:UIControlStateSelected];
[btn setTitle:@"Stop" forState:UIControlStateNormal];
- (IBAction) restartPressed:(UIButton *)btn {
btn.selected = !btn.isSelected;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.