问题
I have 5 TabBar views... how do I select which view appears when the app first starts? (I have some computations using data that is null at app start time). The app crashes BEFORE it even gets to FinishedLaunching! And how does it determine which view is going to be the first one?
One previous answer I got suggested tabBarController.SelectedIndex = 0; (I'm using MonoTouch) but didn't tell me where to place it.
回答1:
var u = new UIViewController[]
{
tab1,
tab2,
tab3,
tab4,
tab5,
};
this.ViewControllers = u;
this.SelectedViewController = tab1;
I typically sub-class the UITabBarController and add the code above in the ViewDidAppear method that I override.
回答2:
You should create your view controllers in ViewDidLoad of the UITabBarController, not in the ViewDidAppear. I use the code below (first part is in your AppDelegate class):
// WARNING: Do not make these variables local. MonoTouch will loose the reference to them!
private UIWindow _mainWindow;
private MainTabBarController _mainTabBarController;
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
_mainWindow = new UIWindow(UIScreen.MainScreen.Bounds);
_mainTabBarController = new MainTabBarController();
_mainWindow.AddSubview(_mainTabBarController.View);
_mainWindow.MakeKeyAndVisible ();
return true;
}
Your MainTabBarController class should look like this:
public class MainTabBarController : UITabBarController
{
public override void ViewDidLoad ()
{
ViewControllers = new UIViewController[]
{
new ViewControllerTab1(),
new ViewControllerTab2(),
new ViewControllerTab3(),
new ViewControllerTab4(),
new ViewControllerTab5()
};
SelectedIndex = 2;
}
}
This will show Tab3 (with index 2) at startup.
ViewControllerTab1 etc. are classes derived from eg. UIViewController or UINavigationController which implement their user interface in their own ViewDidLoad()
来源:https://stackoverflow.com/questions/4565153/monotouch-how-to-select-initial-view-from-tabbarcontrollers-multiple-views