Make UIButton's state change to UIControlStateSelected on TouchUp

999 Views Asked by At

I've noticed that if I do something like this

[self setTitle:@"Follow" forState:UIControlStateNormal];
[self setTitle:@"Following" forState:UIControlStateSelected];

The button will start off with "Follow". I press it, and when I release my finger (touch up event) it changes to "Following". That's great. However, when It's now selected and I press it, it immediately changes to "Follow" before I release my finger (on a touch down event). I want to change when I release my finger (touch up event). How do I do this? I am using UIControlStates for a UIButton's title, images, and title color.

Below is my event handler:

- (void)followButtonAction:(UIButton *)button
{
    button.selected = !button.selected;
}

and I set it as so:

[self.followButton addTarget:self action:@selector(followButtonAction:) forControlEvents:UIControlEventTouchUpInside];
2

There are 2 best solutions below

4
Malav Soni On

try to use this, This works for me as toggle button.

-(IBAction)buttonTapped:(UIButton *)sender{
    if ([sender isSelected]) {
        [sender setSelected:NO];
    }else{
        [sender setSelected:YES];
    }
}

Hope this works for you too.

1
JVillella On

Turns out the solution is to add another control state specifically for the combination that is causing the problem (when selected, and then being pressed). Below is the solution:

[self setTitle:@"Follow" forState:UIControlStateNormal];
[self setTitle:@"Following" forState:UIControlStateSelected];
[self setTitle:@"Following" forState:UIControlStateSelected | UIControlStateHighlighted];