简体   繁体   中英

UIButton Response to Touch Down Event

I'm trying to mimic the button behavior of iPhone's Stopwatch app. So I added the following code to Touch Down event of the button.

if ([sender.titleLabel.text isEqualToString:@"Start"])
{
    [sender setTitle:@"Stop" forState:UIControlStateNormal];
    [sender setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
}
else
{
    [sender setTitle:@"Start" forState:UIControlStateNormal];
    [sender setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
}

But the problem is that the text and color don't change as soon as the button is pressed down, which I understand because of what I have as state, forState:UIControlStateNormal. Therefore, in the code above I replaced

forState:UIControlStateNormal 

everywhere with

forState:UIControlStateHighlighted|UIControlStateNormal

But now the problem is that for as long as button is pressed down, it shows 'Stop' but as soon as I release the button it switches back to 'Start'. I don't understand this behavior. Any help will be appreciated.

Try to delete the UIControlStateNormal from here:

forState:UIControlStateHighlighted|UIControlStateNormal

and keep only

forState:UIControlStateHighlighted

EDIT:

Just another thing you can try is to create an integer_t variable (on your ViewDidLoad and set it to 2) and increase it everytime the button is pressed and check if the number is even or odd. Code should be something like this:

if (intVariable % 2 == 0)
{
    [sender setTitle:@"Stop" forState:UIControlStateHighlighted|UIControlStateNormal];
    [sender setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted|UIControlStateNormal];

}
else
{
    [sender setTitle:@"Start" forState:UIControlStateHighlighted|UIControlStateNormal];
    [sender setTitleColor:[UIColor greenColor] forState:UIControlStateHighlighted|UIControlStateNormal];

}
intVariable++;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM