Question

My app's storyboard looks like this.

enter image description here

There is a list of websites defined in an array in the PageViewController. What I'm now trying to do is to let the user type the index number in the textfield in the MainViewController and when you tap the button, in the page view controller, display the corresponding website from the array.Below is my code (I know there are flaws in this app. This is just a demo),

PageViewController.m

#import "MainViewController.h"
#import "PageViewController.h"

@interface MainViewController ()

@property (nonatomic, assign) NSInteger selectedIndex;

@end

@implementation MainViewController

- (IBAction)buttonPressed:(id)sender
{
    self.selectedIndex = [self.textField.text integerValue];
    [self performSegueWithIdentifier:@"ToNext" sender:nil];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    PageViewController *pageVC = [segue destinationViewController];
    pageVC.index = self.selectedIndex;
}

@end

The selectedIndex property gets the number the user types in correctly. The problem arises when it's passed on to the pageVC.

I have another property called index of NSInteger type in the PageViewController to retrieve the passed in value. The problem is it always shows 0.

Can anybody tell me what I'm missing here? I'd really appreciate any suggestion.

I have also uploaded a project demonstrating my issue here in case if my question isn't too clear.

Était-ce utile?

La solution

In your code remove :

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self createPages];
    self.dataSource = self;

    NSLog(@"Index = %lu", self.index);
    [self setViewControllers:[NSArray arrayWithObject:self.pages[self.index]] direction:UIPageViewControllerNavigationDirectionForward animated:true completion:nil];
}

and replace it by :

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self createPages];
    self.dataSource = self;

    NSLog(@"Index = %d", self.index);
    [self setViewControllers:[NSArray arrayWithObject:self.pages[self.index]] direction:UIPageViewControllerNavigationDirectionForward animated:true completion:nil];
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top