1

メインの ViewController に UITableView があります。以下に示すように、Tableview はサブクラスです。ユーザーが行を選択したら、メインの ViewController でルーチンを呼び出して新しいビューに切り替えたいと思います。ただし、サブクラスからメインのビューコントローラーにアクセスできません。これについてどうすればよいですか?

public class TableSource : UITableViewSource
{
    string[] tableItems;
    string cellIdentifier = "TableCell";

    public TableSource(string[] items)
    {
        tableItems = items;
    }
    public override int RowsInSection(UITableView tableview, int section)
    {
        return tableItems.Length;
    }
    public override UITableViewCell GetCell(UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
    {
        UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier);
        if (cell == null)
            cell = new UITableViewCell(UITableViewCellStyle.Default, cellIdentifier);
        cell.TextLabel.Text = tableItems[indexPath.Row];
        return cell;
    }

    public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
    {
        new UIAlertView("Row Selected", tableItems[indexPath.Row], null, "OK", null).Show();
        tableView.DeselectRow(indexPath, true);

        //Call routine in the main view controller to switch to a new view

    }

}
4

3 に答える 3

1

.ctorに追加します。例:

public TableSource(string[] items)

になります:

public TableSource(string[] items, UIViewController ctl)

次に、それへの参照を保持します。

public TableSource(string[] items, UIViewController ctl)
{
    tableItems = items;
    controller = ctl;
}

RowSelectedそしてあなたの呼び出しでそれを使用してください:

public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
    new UIAlertView("Row Selected", tableItems[indexPath.Row], null, "OK", null).Show();
    tableView.DeselectRow(indexPath, true);
    controller.DoWhatYouNeedWithIt ();
}
于 2013-02-21T17:52:04.743 に答える
1

NSNotificationsは別のオプションかもしれません。

したがって、RowSelected で通知を投稿します。

NSNotificationCenter.DefaultCenter.PostNotificationName("RowSelected", indexPath);

ビュー コントローラーでは、通知用のオブザーバーを追加します。

public override void ViewDidLoad()
{
    base.ViewDidLoad();    
    NSNotificationCenter.DefaultCenter.AddObserver(new NSString("RowSelected"), RowSelected);
}

void RowSelected(NSNotification notification) 
{
    var indexPath = notification.Object as NSIndexPath;
    // Do Something
}
于 2016-11-08T19:46:11.160 に答える