MonoTouch, TableViewControllers and SegmentedControl

I've been holding off blogging about MonoTouch recently (tho I've said a bit on twitter) - mostly because the "project" I'm "working" on (read: spare time, but exciting) is something I may not be able to legally release into the app store (and if not, it'll be on github as open source). But in the meantime, I thought I'd share this little nugget.

I've seen, in a number of applications, the use of the SegmentedControl in the header / title of a TableViewController. Something like this, from the Guardian app:

I thought this would be hard - some kind of cloned, custom TableViewController or something. But no, the solution (well, my solution, which may not be the official one) really shows just how well thought out Cocoa and CocoaTouch is:

In your ViewDidLoad method:

this.NavigationItem.TitleView = MakeSegmentedControl();

And the MakeSegmentedControl method looks like this:

public UISegmentedControl MakeSegmentedControl() { UISegmentedControl seg = new UISegmentedControl(new RectangleF(0, 0, 200, 25));

seg.InsertSegment("Highlights", 0, false); seg.InsertSegment("Popular", 1, false); seg.SelectedSegment = 0;

seg.ControlStyle = UISegmentedControlStyle.Bar;

seg.ValueChanged += delegate(object sender, EventArgs e) { if (seg.SelectedSegment == 0) { (TableView.Source as DataSource).LoadPrograms(IplayerConst.HighlightsFeedUrl); } else { (TableView.Source as DataSource).LoadPrograms(IplayerConst.MostPopularFeedUrl); } return seg; }

And the end result looks like this:

Easy and painless.

Nic Wise

Nic Wise

Auckland, NZ