Jak nawigować z jednego kontrolera widoku do drugiego za pomocą Swift


84

Chciałbym przejść z jednego kontrolera widoku do drugiego. Jak mogę przekonwertować następujący kod Objective-C na Swift?

UIViewController *viewController = [[self storyboard] instantiateViewControllerWithIdentifier:@"Identifier"];
UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:viewController];
[self.navigationController pushViewController:navi animated:YES];

Odpowiedzi:


208

Utwórz plik Swift (SecondViewController.swift) dla drugiego kontrolera widoku iw odpowiedniej funkcji wpisz to:

let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as SecondViewController
self.navigationController.pushViewController(secondViewController, animated: true)


Swift 2+

let mapViewControllerObj = self.storyboard?.instantiateViewControllerWithIdentifier("MapViewControllerIdentifier") as? MapViewController
self.navigationController?.pushViewController(mapViewControllerObj!, animated: true)

Szybki 4

let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "IKDetailVC") as? IKDetailVC
self.navigationController?.pushViewController(vc!, animated: true)

@ audrey, cześć, jak ustawić navigationController?
Sanjivani,

@Sanjivani, Cześć, twój kontroler widoku można utworzyć za pomocą Storyboard i przypisać pierwszy kontroler ViewController jako rootViewController. Twoja klasa kontrolera nawigacji (swift) będzie wyglądać następująco:import UIKit class SwiftNavigationController: UINavigationController { init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // Custom initialization }`` override func viewDidLoad() { super.viewDidLoad() }
Audrey Sobgou Zebaze

3
Miałem też ten sam problem, utknąłem przy nawigacji z jednego ViewController do drugiego. Kiedy wypróbowałem ten kod, otrzymuję ten błąd: unexpectedly found nil while unwrapping an Optional valuew drugim wierszu kodu. Proszę o pomoc
Raghavendra

1
Mam problem z parametrem animated: w następujący sposób: „Nie można przekonwertować typu wyrażenia '$ T7 ??' aby wpisać „BooleanLiteralConvertible” ”.
Morkrom

2
Musisz upewnić się, że kontrolery są osadzone w NavigationController, aby to działało, w przeciwnym razie wystąpią błędy.
kakubei

35

Z mojego doświadczenia navigationControllerwynika, że ​​nie ma, więc zmieniłem kod na ten:

let next = self.storyboard?.instantiateViewControllerWithIdentifier("DashboardController") as! DashboardController
self.presentViewController(next, animated: true, completion: nil)

Nie zapomnij ustawić ViewController StoryBoard Idw StoryBoard->identity inspector


2
Dzieje się tak, ponieważ kontroler widoku nie został zwolniony w kontrolerze widoku nawigacji.
Francis Reynolds

18

Jeśli nie chcesz, aby pojawił się przycisk Wstecz (tak było w moim przypadku, ponieważ chciałem przedstawić po zalogowaniu użytkownika), oto jak ustawić root kontrolera nawigacyjnego:

let vc = self.storyboard?.instantiateViewControllerWithIdentifier("YourViewController") as! YourViewController
        let navigationController = UINavigationController(rootViewController: vc)
        self.presentViewController(navigationController, animated: true, completion: nil)

16

SWIFT 3.01

let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "Conversation_VC") as! Conversation_VC
self.navigationController?.pushViewController(secondViewController, animated: true)

7

W szybkim 4.0

var viewController: UIViewController? = storyboard().instantiateViewController(withIdentifier: "Identifier")
var navi = UINavigationController(rootViewController: viewController!)
navigationController?.pushViewController(navi, animated: true)

4

Szybki 3

let secondviewController:UIViewController =  self.storyboard?.instantiateViewController(withIdentifier: "StoryboardIdOfsecondviewController") as? SecondViewController

self.navigationController?.pushViewController(secondviewController, animated: true)

4

W Swift 4.1 i Xcode 10

Tutaj AddFileViewController jest drugim kontrolerem widoku.

Identyfikator scenorysu to AFVC

let next = self.storyboard?.instantiateViewController(withIdentifier: "AFVC") as! AddFileViewController
self.present(next, animated: true, completion: nil)

//OR

//If your VC is DashboardViewController
let dashboard = self.storyboard?.instantiateViewController(withIdentifier: "DBVC") as! DashboardViewController
self.navigationController?.pushViewController(dashboard, animated: true)

W razie potrzeby użyj gwintu.

Dawny:

DispatchQueue.main.async { 
    let next = self.storyboard?.instantiateViewController(withIdentifier: "AFVC") as! AddFileViewController
    self.present(next, animated: true, completion: nil) 
}

Jeśli chcesz się przenieść za jakiś czas.

DAWNY:

//To call or execute function after some time(After 5 sec)
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
    let next = self.storyboard?.instantiateViewController(withIdentifier: "AFVC") as! AddFileViewController
    self.present(next, animated: true, completion: nil) 
} 

2

Szybko 3

let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "NextViewController") as! NextViewController        
self.navigationController?.pushViewController(nextVC, animated: true)

2
let objViewController = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
self.navigationController?.pushViewController(objViewController, animated: true)

Czy mógłbyś krótko wyjaśnić, co robi twój kod, dlaczego rozwiązuje problem i czym różni się od wszystkich innych odpowiedzi.
JJJ

tutaj używam identyfikatora scenorysu jako identyfikatora. Za pomocą referencji (objViewController) przenieś kontrolkę do klasy View Controller
Davender Verma

2
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let home = storyBoard.instantiateViewController(withIdentifier: "HOMEVC") as! HOMEVC
navigationController?.pushViewController(home, animated: true);

Myślę, że to nie jest składnia Swift ani Objc
SPatel

1

Szybki 4

Możesz przełączyć ekran naciskając kontroler nawigacyjny, najpierw musisz ustawić kontroler nawigacyjny z UIViewController

let vc = self.storyboard?.instantiateViewController(withIdentifier: "YourStoryboardID") as! swiftClassName

self.navigationController?.pushViewController(vc, animated: true)

1

Szybki 5

Użyj Segue, aby przeprowadzić nawigację z jednego kontrolera widoku do innego kontrolera widoku:

performSegue(withIdentifier: "idView", sender: self)

Działa to na Xcode 10.2.


rodzaj ścieku?
developper

1

W AppDelegate możesz pisać w ten sposób ...

var window: UIWindow?

fileprivate let navigationCtrl = UINavigationController()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    self.createWindow()

    self.showLoginVC()

    return true
}

func createWindow() {
    let screenSize = UIScreen.main.bounds
    self.window = UIWindow(frame: screenSize)
    self.window?.backgroundColor = UIColor.white
    self.window?.makeKeyAndVisible()
    self.window?.rootViewController = navigationCtrl
}

func showLoginVC() {
    let storyboardBundle = Bundle.main
    // let storyboardBundle = Bundle(for: ClassName.self) // if you are not using main application, means may be you are crating a framework or library you can use this statement instead
    let storyboard = UIStoryboard(name: "LoginVC", bundle: storyboardBundle)
    let loginVC = storyboard.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC
    navigationCtrl.pushViewController(loginVC, animated: false)
}
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.