Last active
January 5, 2021 14:31
-
-
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#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just replace the "TableView" prefix with whatever you want to call your controller.