MonoTouch Sample Code: UITableView

I’m just going to come right out and say it: I hate Objective-C. In Introduction to The Objective-C 2.0 Programming Language, Apple writes:

The Objective-C language is a simple computer language designed to enable sophisticated object-oriented programming. Objective-C is defined as a small but powerful set of extensions to the standard ANSI C language. Its additions to C are mostly based on Smalltalk, one of the first object-oriented programming languages. Objective-C is designed to give C full object-oriented programming capabilities, and to do so in a simple and straightforward way.

Apparently, that’s true for plenty of Mac and iPhone developers, but not me. I find Objective-C to be ugly, verbose, and confusing. Interface Builder and the whole Cocoa UI event system also leave me cold. MonoTouch is a life saver. It lets me use C# and .Net idioms to develop native iPhone applications. Yes, you’ll still need a Mac. Currently, MonoTouch is in beta. There are of course a few bugs, but the design is beautiful and the developers very responsive. I especially like how MonoTouch integrates the SDK and .Net type systems and events and implements Objective-C delegates.

OK, enough praise for MonoTouch. The real reason for this post is to publish a simple example of using MonoTouch and C# to use a UITableView in an iPhone app. Though you can use Interface Builder with MonoTouch, this example shows how to use a UITableView programmatically.

This was useful for me to learn how to use UITableView initially without a lot of other code. For more details on building the main application and controller, see the MonoTouch sample programs and tutorials.

You’ll also want to read Apple’s Table View Programming Guide for the iPhone OS and UITableView class reference. They’re really quite good. Consequently, I suggest you learn at least enough about Objective-C, Xcode, and Interface Builder to understand Apple’s developer resources.

Update 10/10/09: Fixed the code display.

Here’s the sample code:

/*
Copyright (c) 2009, Terry Westley

Copying and distribution of this file, with or without
modification, are permitted in any medium without royalty.
This file is offered as-is, without any warranty.
*/

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;

using MonoTouch.Foundation;
using MonoTouch.UIKit;

namespace MT_SampleTableView
{
    public class Application
    {
        static void Main (string[] args)
        {
            UIApplication.Main (args, null, "AppController");
        }
    }

    [Register ("AppController")]
    public class AppController : UIApplicationDelegate
    {
        UIWindow window;

        public override bool FinishedLaunching (
            UIApplication app, NSDictionary options)
        {
            // Create the main view controller
            var vc = new MainViewController ();

            // Create the main window and add main view
            // controller as a subview
            window = new UIWindow (UIScreen.MainScreen.Bounds);
            window.AddSubview(vc.View);

            window.MakeKeyAndVisible ();
            return true;
        }

        // This method is allegedly required in iPhoneOS 3.0
        public override void OnActivated (
            UIApplication application)
        {
        }
    }

    [Register]
    public class MainViewController : UIViewController
    {
        private UITableView tableView;
        private List<string> list;

        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();

            list = new List<string>()
            {
                "Tangerine",
                "Mango",
                "Grapefruit",
                "Orange",
                "Banana"
            };

            tableView = new UITableView()
            {
                Delegate = new TableViewDelegate(list),
                DataSource = new TableViewDataSource(list),
                AutoresizingMask =
                    UIViewAutoresizing.FlexibleHeight|
                    UIViewAutoresizing.FlexibleWidth,
                BackgroundColor = UIColor.Yellow,
            };

            // Set the table view to fit the width of the app.
            tableView.SizeToFit();

            // Reposition and resize the receiver
            tableView.Frame = new RectangleF (
                0, 0, this.View.Frame.Width,
                this.View.Frame.Height);

            // Add the table view as a subview
            this.View.AddSubview(tableView);

            Console.Write("If you're using the simulator, ");
            Console.WriteLine("switch to it now.");
        }

        private class TableViewDelegate : UITableViewDelegate
        {
            private List<string> list;

            public TableViewDelegate(List<string> list)
            {
                this.list = list;
            }

            public override void RowSelected (
                UITableView tableView, NSIndexPath indexPath)
            {
                Console.WriteLine(
                    "TableViewDelegate.RowSelected: Label={0}",
                     list[indexPath.Row]);
            }
        }

        private class TableViewDataSource : UITableViewDataSource
        {
            static NSString kCellIdentifier =
                new NSString ("MyIdentifier");
            private List<string> list;

            public TableViewDataSource (List<string> list)
            {
                this.list = list;
            }

            public override int RowsInSection (
                UITableView tableview, int section)
            {
                return list.Count;
            }

            public override UITableViewCell GetCell (
                UITableView tableView, NSIndexPath indexPath)
            {
                UITableViewCell cell =
                    tableView.DequeueReusableCell (
                        kCellIdentifier);
                if (cell == null)
                {
                    cell = new UITableViewCell (
                        UITableViewCellStyle.Default,
                        kCellIdentifier);
                }
                cell.TextLabel.Text = list[indexPath.Row];
                return cell;
            }
        }
    }
}
About these ads
This entry was posted in iPhone Dev and tagged , , , , , . Bookmark the permalink.

19 Responses to MonoTouch Sample Code: UITableView

  1. Pingback: MonoTouch.Info

  2. Richard says:

    Great starting point. Can’t get used to the Interface Builder, so am creating my interface myself.

  3. CraigD says:

    When I built this a compiler error occurs: “Type type or namespace ‘List’ could not be found. Are you missing a using directive or an assembly reference? (CS0246)”

    I think your blog editor has stripped out >string< – what appears to be a declaration for a List class should in fact be a generic List of type string (ie. everywhere that List appears above, it should be List<string>)

    Hopefully this comment hasn’t also had the angle-brackets stripped…

  4. twestley says:

    @CraigD: Thanks for noticing. Yes, it’s the blog software that removes it. I had to insert the & lt ; and & gt ; to get it to work. I had forgotten that these were exceptions in the <pre> element. Browsers would have removed it anyway.

    Hmm, I did like this free WordPress.com blogging site when I first started, but it’s not very good for publishing code. Oddly, the support page (http://en.support.wordpress.com/code/) shows code nicely blocked off. Apparently the support site “payed” for custom CSS!

  5. Max says:

    Hi, i don’t show the text of cell (UITableViewCell).
    can you help me ?

  6. twestley says:

    Check what you’re doing in the class TableViewDataSource. I believe that is they key to displaying text. Try to imitate what Apple has done in the documents referenced above: Table View Programming Guide for the iPhone OS and UITableView class reference.

    If that doesn’t help, post your code in a comment here. See my comment about how to post code in a WordPress blog comment.

  7. Max says:

    Hi, it seems that the cell text is not display, because if i click on the cell the RowSelected Method of UITableViewDelegate is raised.

    I use the follow instruction :
    cell.TextLabel.Text =”TEST”;

    the ‘TEST’ is not displayed…
    Can you help me ?

  8. twestley says:

    The cell text should be displayed even before you click on the cell.

    Are you trying to change the text in the RowSelected method of your UITableViewDelegate? It needs to be done in the GetCell method of the UITableViewDataSource as shown in the sample code above.

    If I’m way off in guessing what you’re doing, why don’t you go ahead and post more of the code so we can see the context of what you’re doing.

  9. Pingback: Fun with Monotouch and Multi-Level Table Views without Interface Builder - KevFoo

  10. Anand says:

    Hi – I used your code and got the following error when trying to run this code in MonoDevelop – setValue:forUndefinedKey this class is not key value coding-compliant for the key TableView. Do you know what might be causing this issue? Please let me know.

  11. Jonas B says:

    Hi, I’m having similar problems to Max – the delegate.RowSelected is called when I click on the screen, but nothing is visible; no texts, no lines, just a while background.

    I had to make a few changes to the UIApplicationDelegate part of your code (to fit the template – public partial class AppDelegate etc), but otherwise it’s intact.

    Any ideas..? (OSX10.5.8/iPhoneSDK3.1.2/MD2.2/MT1.4.5)
    Thanks!

  12. Jonas B says:

    Found it – in the new iPhone project template, “window” has already been instantiated elsewhere, so the second instantiation on line 41 needs to be removed.

  13. Stu says:

    Can’t agree more on Objective C and interface builder… objective C is really objectionalable

  14. Kartikk says:

    Good to hear that there are more teachers joining in the initiative of teaching a fun platforming that is rewarding and can build and get results for students in a short span of time – if they dedicate themselves and come up with unique app ideas. That said, there is still a shortage of well structured courses and one-on-one help that many of the aspiring noobs seek. This is one training institute that is changing that, with their start-to-finish iPhone/Android Application Development Online Course. Head over to http://www.edumobile.org/242-5.html to get more information (they have a weekly remote learning system setup).

  15. Andy says:

    I’ve only read the first paragraph for now, but finally I’ve found out I’m not mad. IB is a pain in the *** and the entire paradigm of Obj-C looks annoying when you’ve already got used to C#.

    Thanks

  16. twestley says:

    I’ve now gotten used to Objective-C. I switched when it looked like Mono would be killed by Apple. I doubt that I’ll switch back to Mono now that I’m comfortable with Objective-C. I still don’t use IB though.

  17. Pingback: leetcoders

  18. Steve says:

    Thanks for the tutorial. I couldn’t agree more, Objective-C is one of my least favorite languages. Unless you write exclusively for the Apple platform, I can’t see a good reason to become proficient in OC.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s