[英]transitioning from one view controller to another using a button
因此,我創建了具有基本邏輯的登錄頁面。 如果用戶名和/或密碼為空,則顯示錯誤消息。 如果已滿,則過渡到下一頁(主頁)。 我在情節提要板上創建了第二個ViewController,並創建了SecondViewController”。然后將各自的ViewController類定義為“ SecondViewController”。
在第一個ViewController.swift文件中,我使用了以下代碼:
func transition(Sender:UIButton!)
{
let secondViewController: SecondViewController = SecondViewController()
self.presentViewController(secondViewController, animated:true, completion:nil)
}
但是,當我對其進行測試時,按登錄按鈕(同時填寫用戶名和密碼時)會將我轉移到黑屏,而不是第二個View Controller。 有什么想法做什么?
您不能僅使用默認的init方法來初始化視圖控制器。
您可能應該在情節提要中創建一個視圖控制器場景,在其上添加一個唯一的標識符,使用instantiateViewControllerWithIdentifier:
實例化它,然后像執行操作一樣顯示它。
您需要在情節提要中的視圖控制器之間進行self.performSegueWithIdentifier()
,然后調用self.performSegueWithIdentifier()
。
或者,您也可以給UIViewController一個標識符,並以編程方式顯示它:
let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
let secondViewController storyboard.instantiateViewControllerWithIdentifier("") as? SecondViewController
if let secondViewController = secondViewController {
self.presentViewController(secondViewController, animated:true, completion:nil)
}
如果希望視圖包含在情節提要板上添加的內容,則可以為其提供一個情節提要ID(在情節提要中設置視圖控制器的類的下面的幾個框)。
例如,如果給它提供ID“ secondVC”,則可以使用以下命令創建它:
let secondViewController = storyboard?.instantiateViewControllerWithIdentifier("secondVC") as? SecondViewController
基本上有三種方法可以做到這一點
1)在情節提要中創建segue,盡管只有在該項目中只有一個segue時,此方法才能起作用
2)在您呈現的視圖控制器中使用prepareforSegue和performSegue方法重寫func prepareForSegue(segue:UIStoryboardSegue,sender:AnyObject?){
if segue.identifier == "YourIdentifier" {
let controller = segue.destinationViewController as!secondViewController
}
}
然后在您的IBACtion中使用它
performSegueWithIdentifier("YourIdentifier", sender:sender)
3)(推薦一個)
let controller = self.storyboard?.instantiateViewControllerWithIdentifier("ContactsVC")! as! ContactsVC
self.presentViewController(controller, animated:true, completion:nil
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.