Paging controllers with MonoTouch

Posted by ESCOZ on Monday, February 15, 2010

I have just pushed a new control into my open source collection of MonoTouch controls, called PagedViewController.

I created this control during the development of my new iPhone application, Cracklytics (available soon in the AppStore, recommended!) mainly to simplify the usage of the UIScrollView to make applications that use pagination, such as the Apple’s Weather app.

Usage of the control is quite simple. All you need to do is create a new object of type PagedViewController, and pass a data source to it, like below (executed from inside a UIViewController):

var pagedViewController = new PagedViewController{
    PagedViewDataSource = new TestPagesDataSource()

The most important part of the code is the actual implementation of the TestPagesDataSource, used above. The class works as a factory of UIViewControllers, much like a UITableViewDataSource is used by the UITableViewControllers. The class needs to implement the IPagedViewDataSource interface, like the sample implementation below:

public class TestPagesDataSource : IPagedViewDataSource {
    private List _colors = new List{

    public int Pages {get {return 4;} }

    public UIViewController GetPage(int i){
        UIViewController c = new UIViewController();
        c.View.BackgroundColor = _colors[i];
        c.View.AddSubview(new UILabel{
                Text= "Swipe to change view",
                TextAlignment = UITextAlignment.Center,
                Frame = new RectangleF(0,0,320,100),
                BackgroundColor = UIColor.Clear
        return c;

    public void Reload(){}

The most important methods there are the Pages counter and the GetPage(int i), which should return a new UIViewController. The Reload() method is called automatically when the Reload() method of the PagedViewController is called; you can use this to, for example, load more data from the web, or from a local database.

The control currently works fine if you don’t have lots of pages, probably a few dozen, because the controller automatically loads all the pages during startup. If you have more than that, though, the pages would end up using too much memory, so you would have to modify the controller so that only the current page, as well as the previous and the next pages are loaded.

To see this control working, download the entire solution from github.