Xamarin iOS - Load Storyboard Reference Programatically

北慕城南 提交于 2020-06-11 06:51:19

问题


I have 2 storyboards: Activities.storyboard and Contacts.storyboard.

On Contacts.storyboard I have a ViewController: ContactDetails.

On Activities.storyboard I need refer the ContactDetails in Contacts.storyboard

I created a Storyboard Reference on Activities.storyboard and referenced the ContactDetails.

And I tried load this View Controller programmatically

var viewController = Storyboard.InstantiateViewController(nameof(ContactDetails));
NavigationController.PushViewController(viewController, true);

But I didn't work to load programmatically as a normal View Controller

Foundation.MonoTouchException: Objective-C exception thrown. Name: NSInvalidArgumentException Reason: Storyboard () doesn't contain a view controller with identifier 'ContactDetails'

I know it works this way:

var storyboard = UIStoryboard.FromName(nameof(Contact), null);
var viewController = storyboard.InstantiateViewController(nameof(ContactDetails));
NavigationController.PushViewController(viewController, true);

But I want to use a Reference View Controller, is it possible?


回答1:


If you use the Storyboard ID, it can also be used as a 'restoration identifier' and allows you to instantiate from your storyboard. I would suggest using this approach, it tends to be the simplest way to achieve what you're trying to do.

It's also worth noting that you have to cast the instantiated UIViewController to it's type (at least I find it makes life easier if I want to pass across variables and such.)

ContactDetails viewController = Storyboard.InstantiateViewController(nameof(ContactDetails)) as ContactDetails;

OR

ContactDetails viewController = Storyboard.InstantiateViewController("ContactDetails") as ContactDetails;

It's also worth noting that Xamarin iOS 'Storyboard' property of the UIViewController automatically determines the Storyboard reference, and it's worth checking that it is definitely bringing you the pointer to the 'Contact' storyboard (as multiple storyboards are of course possible in iOS development should you choose.)




回答2:


Apparently the only way to load Storyboard Reference is with Segue.

Programmatically the only way is instantiate the Storyboard and after instantiate the ViewController

Like this:

var storyboard = UIStoryboard.FromName(nameof(Contact), null);
var viewController = storyboard.InstantiateViewController(nameof(ContactDetails));
NavigationController.PushViewController(viewController, true);


来源:https://stackoverflow.com/questions/42904487/xamarin-ios-load-storyboard-reference-programatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!