Как перемещаться с одного контроллера просмотра на другой с помощью Swift
Я хотел бы перейти от одного контроллера представления к другому. Как преобразовать следующий код Objective-C в Swift?
UIViewController *viewController = [[self storyboard] instantiateViewControllerWithIdentifier:@"Identifier"];
UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:viewController];
[self.navigationController pushViewController:navi animated:YES];
Ответы
Ответ 1
Создайте файл swift (SecondViewController.swift) для второго контроллера представления и в соответствующей функции введите:
let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as SecondViewController
self.navigationController.pushViewController(secondViewController, animated: true)
Свифт 2+
let mapViewControllerObj = self.storyboard?.instantiateViewControllerWithIdentifier("MapViewControllerIdentifier") as? MapViewController
self.navigationController?.pushViewController(mapViewControllerObj!, animated: true)
Swift 4
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "IKDetailVC") as? IKDetailVC
self.navigationController?.pushViewController(vc!, animated: true)
Ответ 2
В моем опыте navigationController
было nil, поэтому я изменил свой код на это:
let next = self.storyboard?.instantiateViewControllerWithIdentifier("DashboardController") as! DashboardController
self.presentViewController(next, animated: true, completion: nil)
Не забудьте установить ViewController StoryBoard Id
в StoryBoard
→ identity inspector
Ответ 3
Если вы не хотите, чтобы кнопка возврата появлялась (что было моим делом, потому что я хотел представить после входа пользователя в систему), вот как установить корень контроллера nav:
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("YourViewController") as! YourViewController
let navigationController = UINavigationController(rootViewController: vc)
self.presentViewController(navigationController, animated: true, completion: nil)
Ответ 4
SWIFT 3.01
let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "Conversation_VC") as! Conversation_VC
self.navigationController?.pushViewController(secondViewController, animated: true)
Ответ 5
В быстрой версии 4.0
var viewController: UIViewController? = storyboard().instantiateViewController(withIdentifier: "Identifier")
var navi = UINavigationController(rootViewController: viewController!)
navigationController?.pushViewController(navi, animated: true)
Ответ 6
Swift 3
let secondviewController:UIViewController = self.storyboard?.instantiateViewController(withIdentifier: "StoryboardIdOfsecondviewController") as? SecondViewController
self.navigationController?.pushViewController(secondviewController, animated: true)
Ответ 7
В Swift 4.1 и Xcode 10
Здесь AddFileViewController является вторым контроллером представления.
Идентификатор раскадровки - 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)
При необходимости используйте нить.
Пример:
DispatchQueue.main.async {
let next = self.storyboard?.instantiateViewController(withIdentifier: "AFVC") as! AddFileViewController
self.present(next, animated: true, completion: nil)
}
Если вы хотите двигаться через некоторое время.
EX:
//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)
}
Ответ 8
let objViewController = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
self.navigationController?.pushViewController(objViewController, animated: true)
Ответ 9
В быстрых 3
let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "NextViewController") as! NextViewController
self.navigationController?.pushViewController(nextVC, animated: true)
Ответ 10
Хорошая функция для UINavagivationController
Пример:
func goToLoginView(){
if let loginView = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as? LoginViewController{
self.pushViewController(loginView, animated: true)
}
}
Ответ 11
Swift 4
Вы можете переключать экран, нажимая навигационный контроллер. Прежде всего, вы должны установить навигационный контроллер с помощью UIViewController.
let vc = self.storyboard?.instantiateViewController(withIdentifier: "YourStoryboardID") as! swiftClassName
self.navigationController?.pushViewController(vc, animated: true)
Ответ 12
Ксамарин (С#)
NavigationController.PushViewController(new HomePage(), true);
Передайте Destination ViewController.
стриж
navigationController?.pushViewController(HomePage(), animated: true);
Ответ 13
Swift 5
Используйте Segue для выполнения навигации от одного View Controller к другому View Controller:
performSegue(withIdentifier: "idView", sender: self)
Это работает на Xcode 10.2.
Ответ 14
В AppDelegate вы можете написать так...
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)
}