Search code examples
iosobjective-cswiftuisplitviewcontroller

How to replace Detail in UISplitViewController in Swift?


Usually I can replace my detail view of splitview by this code in Objective-C:

  [self.splitViewController viewWillDisappear:YES];
  NSMutableArray *viewControllerArray=[[NSMutableArray alloc] initWithArray:[[self.splitViewController.viewControllers objectAtIndex:1] viewControllers]];
  [viewControllerArray removeLastObject];

  [viewControllerArray addObject:self.detailViewController];
  [[self.splitViewController.viewControllers objectAtIndex:1] setViewControllers:viewControllerArray animated:NO];
  [self.splitViewController viewWillAppear:YES];

Try to rewrite it in Swift, but I even can't get the viewControllers in this code:

  NSMutableArray *viewControllerArray=[[NSMutableArray alloc] initWithArray:[[self.splitViewController.viewControllers objectAtIndex:1] viewControllers]];

Swift:

    let test: UIViewController = (self.splitViewController?.viewControllers[1])!

It should have test.viewControllers , but it doesn't as seen in below pic

enter image description here

Does Swift handle the replace in splitview in different way?


Solution

  • This works for me but I am not sure if this is the best practice:

        let detailViewController = self.storyboard?.instantiateViewControllerWithIdentifier("DetailNavigationViewController") as! UINavigationController
        self.splitViewController?.viewControllers[1] = detailViewController
    

    Only need to get the desired viewController and assign it to index 1 of splitViewController