[英]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.