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

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

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

我的程序结构是这样的,在一个页面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,提示这样:




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



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

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

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





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值