0

Here is my setup :

Home page, Profile Page, Friends page.

In each page, there is the exact same segmentend button : [Home | Profile | Friends]

When I tap on a segment, a segue is called and the page changed.

So, when i'm in Profile, Profile is already selected, and i can tap on either Home or Friends ; when i do, the new page is loaded, the new segment is selected and i can do it again if I want to.

In the storyboard, i have only 3 pages with a " a ton " of custom segue (i used custom for animation purposes).

In the code, i have this :

(void)moveToPage
{
    if ([self.pageSwitch selectedSegmentIndex] == 1)
    {
         [self performSegueWithIdentifier:@"fromHomeToProfile" sender:self];;
    }
    if ([self.pageSwitch selectedSegmentIndex] == 2)
    {
         [self performSegueWithIdentifier:@"fromHomeToFriends" sender:self];;
    }

}


- (IBAction)pageSwitchButton:(id)sender {
    [self.pageSwitch addTarget:self
                           action:@selector(moveToPage)
                 forControlEvents:UIControlEventValueChanged];
}

the names are self explanatory.

My problem is (we're getting to it) : When i tap on a segment, it becomes selected, but nothing happens THE FIRST TIME. If i tap a new segment (that is obviously not the one from the current page), then it works just fine. Basically, the first tap is ignored, then the second one works. So i have to tap a page, and then tap another that isn't the same for it to work.

Any idea? I'm kind of stuck with this unique problem :D

Gil Sand
  • 5,333
  • 3
  • 29
  • 66

1 Answers1

0

Okay i actually found it ; i just didn't understand how the addTarget:action:forControlEvents works.

We simply need to put the

[self.pageSwitch addTarget:self
                           action:@selector(moveToPage)
                 forControlEvents:UIControlEventValueChanged];

in the ViewDidLoad and it works just fine. It has to be put in the 3 pages.

Here is the explanation i got IRL, feel free to comment/add stuff if i'm wrong :

The addTarget:action:forControlEvents: method is a behaviour that your page has. " When this happens, do that ". Because it was in my Action, the page only learned the behaviour when i clicked the first time, and knew how to react afterwards. For the page to know what to do the first time, it has to learn the behaviour at the earliest stage of its creation, hence in the ViewDidLoad.

Because there is nothing left in the Action, you can actually remove it completly and remove the links in the storyboard. You just need the outlet and the moveToPage method for this to work.

I hope this helps :)

Gil Sand
  • 5,333
  • 3
  • 29
  • 66