jeroldhaas
2/17/2015 - 5:30 PM

All the boilerplate code needed to get a custom iOS UITableViewController up and running in C#

All the boilerplate code needed to get a custom iOS UITableViewController up and running in C#

public class TableViewController : UITableViewController
{
	static readonly NSString CellId = new NSString ("C");

	readonly TableViewSource source = new TableViewSource ();
	readonly List<string> rows = new List<string> ();

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

		try {
			TableView.RegisterClassForCellReuse (typeof(TableViewCell), CellId);
			source.Controller = this;
			TableView.Source = source;
		} catch (Exception ex) {
			Console.WriteLine (ex);
		}
	}

	async Task OnRowSelectedAsync (int index)
	{
		var r = rows [index];
		// Do something awesome with r
	}

	class TableViewCell : UITableViewCell
	{
		public TableViewCell ()
		{
		}
		public TableViewCell (IntPtr handle) : base (handle)
		{				
		}
		public void Bind (string value)
		{
			DetailTextLabel.Text = value ?? "";
		}
	}

	class TableViewSource : UITableViewSource
	{
		public TableViewController Controller;

		public override nint RowsInSection (UITableView tableview, nint section)
		{
			try {
				return Controller.rows.Count;
			} catch (Exception ex) {
				Console.WriteLine (ex);
				return 0;
			}
		}

		public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
		{
			try {
				var c = (TableViewCell)tableView.DequeueReusableCell (CellId);
				c.Bind (Controller.rows [indexPath.Row]);
				return c;
			} catch (Exception ex) {
				Console.WriteLine (ex);
				return new TableViewCell ();
			}
		}

		public override async void RowSelected (UITableView tableView, NSIndexPath indexPath)
		{
			try {
				await Controller.OnRowSelectedAsync (indexPath.Row);
			} catch (Exception ex) {
				Console.WriteLine (ex);
			}
		}
	}
}