Skip to content

Instantly share code, notes, and snippets.

@praeclarum
Last active January 5, 2021 14:31
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save praeclarum/8852141fcea8a8952d01 to your computer and use it in GitHub Desktop.
Save praeclarum/8852141fcea8a8952d01 to your computer and use it in GitHub Desktop.
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);
}
}
}
}
@praeclarum
Copy link
Author

Just replace the "TableView" prefix with whatever you want to call your controller.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment