Swift를 사용하여 한 View 컨트롤러에서 다른 View 컨트롤러로 이동하는 방법
한 뷰 컨트롤러에서 다른 뷰 컨트롤러로 이동하고 싶습니다.다음 Objective-C 코드를 Swift로 변환하려면 어떻게 해야 합니까?
UIViewController *viewController = [[self storyboard] instantiateViewControllerWithIdentifier:@"Identifier"];
UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:viewController];
[self.navigationController pushViewController:navi animated:YES];
두 번째 보기 컨트롤러에 대한 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)
스위프트 4
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "IKDetailVC") as? IKDetailVC
self.navigationController?.pushViewController(vc!, animated: true)
내 경험으로는navigationController
0이었기 때문에 코드를 다음과 같이 변경했습니다.
let next = self.storyboard?.instantiateViewControllerWithIdentifier("DashboardController") as! DashboardController
self.presentViewController(next, animated: true, completion: nil)
ViewController를 설정하는 것을 잊지 마십시오.StoryBoard Id
에StoryBoard
->identity inspector
사용자가 로그인한 후에 표시하려고 했기 때문에 뒤로 단추를 표시하지 않으려면 다음과 같이 Nav 컨트롤러의 루트를 설정합니다.
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("YourViewController") as! YourViewController
let navigationController = UINavigationController(rootViewController: vc)
self.presentViewController(navigationController, animated: true, completion: nil)
SWIFT 3.01
let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "Conversation_VC") as! Conversation_VC
self.navigationController?.pushViewController(secondViewController, animated: true)
인스위프트 4.0
var viewController: UIViewController? = storyboard().instantiateViewController(withIdentifier: "Identifier")
var navi = UINavigationController(rootViewController: viewController!)
navigationController?.pushViewController(navi, animated: true)
Swift 4.1 및 Xcode 10에서
여기서 AddFileViewController는 두 번째 뷰 컨트롤러입니다.
스토리보드 ID는 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)
}
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let home = storyBoard.instantiateViewController(withIdentifier: "HOMEVC") as! HOMEVC
navigationController?.pushViewController(home, animated: true);
스위프트 3
let secondviewController:UIViewController = self.storyboard?.instantiateViewController(withIdentifier: "StoryboardIdOfsecondviewController") as? SecondViewController
self.navigationController?.pushViewController(secondviewController, animated: true)
인스위프트 3
let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "NextViewController") as! NextViewController
self.navigationController?.pushViewController(nextVC, animated: true)
let objViewController = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
self.navigationController?.pushViewController(objViewController, animated: true)
스위프트 5
Segue를 사용하여 한 View 컨트롤러에서 다른 View 컨트롤러로 이동합니다.
performSegue(withIdentifier: "idView", sender: self)
이것은 Xcode 10.2에서 작동합니다.
Swift 4 및 5의 경우 사용자는 이 방법을 사용할 수 있습니다.
스위프트 5
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyBoard.instantiateViewController(withIdentifier: "YourViewController") as! YourViewController
self.navigationController?.pushViewController(vc, animated: true)
스위프트 4
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "YourViewController") as? YourViewController
self.navigationController?.pushViewController(vc!, animated: true)
Swift 5.0의 모범 사례
더욱 재사용 가능하고 읽기 쉬움
프로토콜 만들기
protocol Storyboarded { }
이제 프로토콜의 확장을 만듭니다.
extension Storyboarded where Self: UIViewController {
static func instantiateFromMain() -> Self {
let storyboardIdentifier = String(describing: self)
// `Main` can be your stroyboard name.
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
guard let vc = storyboard.instantiateViewController(withIdentifier: storyboardIdentifier) as? Self else {
fatalError("No storyboard with this identifier ")
}
return vc
}
}
// Make a ViewController extension to use on all of your ViewControllers
extension UIViewController: Storyboarded {}
사용방법
let vc = MyViewController.instantiateFromMain()
//here you can pass any data to the next view controller. for example we have a variable with name `myString` in our next view contoller and we want to pass the data my `self viewController`
vc.myString = "This string passed by MyViewController"
self.navigationController?.pushViewController(vc, animated: true)
참고:- 스토리보드에 있는 ID와 동일한 ID를 지정해야 합니다.UIViewController
계급이 있었습니다.아래 예를 확인하십시오.
스위프트 4
내비게이션 컨트롤러를 눌러 화면을 전환할 수 있습니다. 먼저 UIViewController를 사용하여 내비게이션 컨트롤러를 설정해야 합니다.
let vc = self.storyboard?.instantiateViewController(withIdentifier: "YourStoryboardID") as! swiftClassName
self.navigationController?.pushViewController(vc, animated: true)
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)
}
Swift 5에 대한 업데이트:
let next = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
self.present(next, animated: true, completion: nil)
두 View 컨트롤러의 스토리보드 ID를 업데이트하는 것을 잊지 마십시오!
언급URL : https://stackoverflow.com/questions/24038215/how-to-navigate-from-one-view-controller-to-another-using-swift
'programing' 카테고리의 다른 글
엑셀 시트의 셀을 프로그래밍 방식으로 포맷하는 방법은? (0) | 2023.08.22 |
---|---|
iOS 다운로드 및 앱 내부 이미지 저장 (0) | 2023.08.22 |
동일한 쿼리에서 DISTINCT 및 TOP 사용 (0) | 2023.08.17 |
C++에서 컴파일 타임 문자열을 편리하게 선언합니다. (0) | 2023.08.17 |
JQuery.trigger에서 매개 변수 전달 중 (0) | 2023.08.17 |