How to navigate to ViewController in Xamarin iOS on RowSelected event

后端 未结 2 517
野的像风
野的像风 2021-01-21 04:59

I am having a TableView on my home screen which is inside a Navigation Controller. Now, when a row is selected, I want to show a MapView.

I want to get access to the Nav

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-21 05:41

    I assume your RowSelected method is in your UITableViewController, right? In this case, it's easy, as you can access the NavigationController property (defined in UIViewcontroller) which is automatically set to the parent UINavigationController

    public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
    {
        var index = indexPath.Row;
        NavigationController.PushViewController (new MyDetailViewController(index));
    }
    

    Now, you probably should use a UITableViewSource, and override RowSelected there. In that case, make sure the UINavigationController is available by doing constructor injection:

    tableViewController = new UITableViewController();
    tableViewController.TableView.Source = new MyTableViewSource (this);
    
    class MyTableViewSource : UITableViewSource
    {
        UIViewController parentController;
        public MyTableViewSource (UIViewController parentController) 
        {
            this.parentController = parentController;
        }
    
        public override int RowsInSection (UITableView tableview, int section)
        {
            //...
        }
    
        public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
        {
            //...
        }
    
        public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
        {
            var index = indexPath.Row;
            parentController.NavigationController.PushViewController (new MyDetailViewController(index));
        }
    }
    

    Replace MyDetailViewController in this generic answer by your MapViewController and you should be all set.

提交回复
热议问题