且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用Swift完成不同View Controller之间的切换

更新时间:2022-04-26 10:19:59

之前用objective-c开发时,页面之间的切换很容易。其实用swift没有很大的变化,如果你是用storyboard完成的界面,基本上是同样的方式,只不过在代码部分写成swift风格的就行了。

今天在实验开发一个简单的小程序时,却遇到了一些bug,后来还是求助***上的大神解决了问题,在此做下记录。

我的程序结构是这样的,在一个页面A中有个按钮,然后点击按钮以后,切换到另一个页面B。A和B都在同一个storyboard中。

这里先说下通用的方法:

  • 手动用代码建好的view controller,即不是在storyboard中建立的:

var vc = ViewController() 
self.presentViewController(vc, animated: true, completion: nil) 
return

  • 在storyboard中建立的可以用下面的代码:

let sb = UIStoryboard(name:"Main", bundle: nil)
let vc = sb.instantiateViewControllerWithIdentifier("tabBarController") as ViewController 
self.presentViewController(vc, animated: true, completion: nil)

这里的tabBarController 是你在storyboard中对相应的viewcontroller打开其identifier inspector,然后对其storyboard ID起的名字。

所以我的程序就是,在A的类中,定义下面的button action:

@IBAction func login(sender: UIButton) {
        let sb = UIStoryboard(name: "Main", bundle: nil)
        let vc = sb.instantiateViewControllerWithIdentifier("tabBarController") as UITabBarController
        self.presentViewController(vc, animated: true, completion: nil)
    }
注意我这里as后并没有写成ViewController,bug就出现在这里。当我最初写的是viewController时,总会出bug,提示这样:


用Swift完成不同View Controller之间的切换

我Google了关于dynamic Cast Class Unconditional也没有找到太多有用的信息,没有办法只有求助***的大神了,很快就有人回复:


用Swift完成不同View Controller之间的切换

原来是因为我从storyboard读到的被命名为tabBarController的控件不能被强制转换(as)成viewcontroller,因为它其实是一个UITabBarController,也就是说,as后面你想要强制转换成的一定要与storyboard中的保持一致。

所以,代码就那么几行,但是不能生搬硬套。

如果你的storyboard中是viewcontroller,就as成viewcontroller,如果是UITabBarController就as成为UITabBarController,如果是其它的诸如UITableViewController,你知道怎么做。