iPhone Dev Tips: View controllers & UIScrollView

25 aprile 2009

Just something I’d better remind next time I pick up with an application development. View controllers are the solid rocks on which everything is built and UIScrollView is easy to use only if you know how.

1. UIViewController

There are four main methods you’ll probably use:

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle

In here you can init all of your data. View is not still loaded so if it’s unarchived from a NIB file all outlets are missing.

- (void)viewDidLoad  

Here your view is loaded ONLY if it’s unarchived from a NIB file. It’s the right place to init all objects loaded from the NIB.

- (void)loadView

Here you NEED to create your view and assign it to the view controller (self.view= whatever) if it’s created programmatically and not loaded from a NIB.

- (void)viewWillAppear:(BOOL)animated

Tables ? Edit field ? Here’s the place for setting the default values and loading data into tables. Remember: it’s called only if the view is not added directly to the view hierarchy. You must pass through the view controller. You know, things like pushNavigationController and so on.

- (void)viewWillDisappear:(BOOL)animated

And this is the right place to save the data you entered in edit fields and other controls to your model.

So you might use them like this:

- (void)viewWillAppear:(BOOL)animated


NSSring *string=[[NSUserDefaults standardUserDefaults] stringForKey:@"MyString"];


- (void)viewWillDisappear:(BOOL)animated


      NSString *string=myEditfield.text;
       [[NSUserDefaults standardUserDefaults] setObject: string forKey:@"MyString"];

2. UIScrollView

In IB create a UIScrollView, drop inside each control and subview you need. Make sure the UIScrollView is big enough to contain all of your items.
In your ViewController.m in viewDidLoad or viewWillAppear (my first chance) write the following code:

[myScrollView setContentSize:CGSizeMake(320,320)];

The most important thing is that the content size must be bigger than the scrollview’s one. Without this excerpt no auto-scrolling !

Go top