サマリ
Xamarin.iOSでTableViewを生成する方法が日本語でまとまっていないと思ったので、まとめました。Xamarin.iOSでは、UITableViewControllerのサブクラスとUITableSourceのサブクラスを使います。C#では2つ以上のクラスの継承ができないため、swiftで書くときのようにDelegateとDataSourceを継承するようなことはしません。
StoryBoard
1.TableViewとTableViewCellをセットする
iOS DesignerかInterface Builderを使って、ViewControllerにTableViewとTableViewCellをセットします。
2.iOS Designerで、TableViewのIdentityのNameをセットする
iOS Designerで、作成したTableViewをクリックします。右下のプロパティにあるIdentityのNameに、任意の値をセットします。UITableViewControllerのサブクラスで使います。私が知る限り、Interface BuilderだとTableViewのIdentityのNameをセットできないですが、もし間違えていたらコメントください。
3.iOS DesignerかInterface BuilderでTableViewCellのIdentifierをセットする
iOS DesignerかInterface Builderで、作成したTableViewCellをクリックします。iOS
Designerだと、右下のプロパティにあるTable View CellのIdentifierに、任意の値をセットします。UITableViewSourceのサブクラスで使います。
Interface BuilderはXCodeの使い方で検索すれば出てきますので割愛。
コード
1.ViewDidLoadで、TableViewのSourceプロパティに、UITableViewSourceを継承したサブクラスのインスタンスをセットする
public override void ViewDidLoad()
{
base.ViewDidLoad();
// 配列でもListでもどちらでも
var list = new List<string>();
TableView.Source = new tableViewSource(list);
}
2.UITableViewSourceクラスを継承したサブクラスを実装する
public class tableViewSource : UITableViewSource
{
readonly List<Item> list = new List<string>();
public SharedTableViewSource(List<string> _list)
{
list = _list;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return list.Count;
}
public override UITableViewCell GetCell(UITableView tableView, Foundation.NSIndexPath indexPath)
{
var cell = tableView.DequeueReusableCell("任意の名前");
var item = list[indexPath.Row];
cell.TextLabel.Text = item.name; // 任意のプロパティ
return cell;
}
}
これでできます。
UITableViewControllerで描画するデータを取得して、Sourceに引き渡したのは、描画するデータが変わったときにEventを取得して、再描画(ReloadData)するためです。ReloadDataはこの例だと、TableView.ReloadData()で実行できます。