LoginSignup
5
3

More than 5 years have passed since last update.

Xamarin.iOSでTableViewを描画する方法

Last updated at Posted at 2017-04-22

サマリ

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()で実行できます。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3