views:

367

answers:

2

I want to initialize 5 viewController's that I want to be able to flick between in a UIScrollView, when my app loads.

+1  A: 

Here is an example of how you can do this:

- (void)loadView {
    [super loadView];

    //standard UIScrollView is added
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    [self.view addSubview:scrollView];

    scrollView.pagingEnabled = YES;
    scrollView.contentSize = CGSizeMake(320*2, 460); //this must be the appropriate size!

    //required to keep your view controllers around
    controllers = [[NSMutableArray alloc] initWithCapacity:0];

    //just adding two controllers
    LabeledViewController *one = [[LabeledViewController alloc] initWithPosition:0 text:@"one"];

    [scrollView addSubview:one.view];
    [controllers addObject:one];
    [one release];

    LabeledViewController *two = [[LabeledViewController alloc] initWithPosition:1 text:@"two"];
    [scrollView addSubview:two.view];
    [controllers addObject:two];
    [two release];  

    [scrollView release];
}

LabeledViewController is pretty simple, but you can add as much to it as you want:

@implementation LabeledViewController

- (id)initWithPosition:(NSInteger)position text:(NSString*)text {
    if( self = [super init] ) {
        myPosition = position;
        myText = [text retain];
    }
    return self;
}


- (void)loadView {
    //this will setup the position in the UIScrollView
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(320*myPosition, 0, 320, 460)];
    self.view = view;
    [view release];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 320, 50)];
    label.text = myText;

    [self.view addSubview:label];
    [label release];
}
bentford
Yep, you can always basically use your view controller as a view via its view property. viewController.view or [viewController view].
Cirrostratus
A: 

You're expressing a want, not asking a question. If your question is "how can I do this", then the answer is "with quite a lot of work", which is not an answer either.

I've done it, but it is not trivial. You are creating a navigation controller and they do things behind the scenes that are not really documented, but can be inferred from view controller behavior. You'll need to create a custom base class (a subclass of UIViewController) which you subclass your regular view controllers from.

Steve Weller