Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I put viewController's into a UIScrollView

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

like image 726
Jab Avatar asked Jan 02 '10 05:01

Jab


People also ask

How do I make my view controller scrollable?

One way to do this is programmatically create an UIScrollView in your UIViewController . To control the scrollability you can set the ScrollView contentSize property.

What is UIScrollView?

UIScrollView is the superclass of several UIKit classes, including UITableView and UITextView . A scroll view is a view with an origin that's adjustable over the content view. It clips the content to its frame, which generally (but not necessarily) coincides with that of the application's main window.


1 Answers

Here is an example of how you can do this:

- (void)viewDidLoad 
{

    //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];

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

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)viewDidLoad 
{
    //this will setup the position in the UIScrollView
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(320*myPosition, 0, 320, 460)];
    self.view = view;

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

    [self.view addSubview:label];
}
like image 77
bentford Avatar answered Sep 28 '22 14:09

bentford