请教swift页面正向传值的问题

yang0123shu 2014-10-29 12:06:50
代码:

@IBAction func toSecond(sender: AnyObject) {
println("ViewController toSecond")
println("\(self.userNameTF.text)")
SecondViewController().secondUserNameTF.text=self.userNameTF.text
self .presentViewController(SecondViewController(), animated: true, completion: nil)

}


问题:fatal error: unexpectedly found nil while unwrapping an Optional value
另外:注释掉传值那句,页面跳转出现问题:Warning: Attempt to present <TurnupTest1.SecondViewController: 0x7ff6f055f190> on <TurnupTest1.ViewController: 0x7ff6f04a5a30> whose view is not in the window hierarchy!

小白求救!!!
...全文
13588 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
sinat_35812387 2016-08-07
  • 打赏
  • 举报
回复
页面传值时关注下页面的生命周期
yang0123shu 2014-11-05
  • 打赏
  • 举报
回复
Great!Get it!谢谢了!
ReyZhang 2014-10-29
  • 打赏
  • 举报
回复
不能直接通过下面的代码来给另外的一个控制器中的UI元素来赋值 SecondViewController().secondUserNameTF.text=self.userNameTF.text 这是因为,你虽然实例化了SecondViewController但 SecondViewController中的UI元素是在loadview 及viewdidload时被加载到内存的。也就是说这时secondUserNameTF这个文本框可能还没有被创建,你这时给它赋值肯定会出问题。 正确的做法: 在SecondViewController中公开一个属性,给这个属性赋值。在SecondViewController的viewdidload中得到这个属性的值,并将这个值赋给secondUserNameTF文本框控件
class  SecondViewController:UIViewController {
        var txtName:String   = ""

        override func viewDidLoad() {
                    secondUserNameTF.text  =  txtName   //////将从上一个控制器传递过来的值赋给文本框
        }
}
toSecond方法应该如下
   @IBAction func toSecond(sender: AnyObject) {
        var secondVC:SecondViewController = SecondViewController()
        secondVC.txtName = self.userNameTF.text
        self .presentViewController(secondVC , animated: true, completion: nil)
    }
yang0123shu 2014-10-29
  • 打赏
  • 举报
回复
有人在吗,怎么像OC那样传值就崩,求解啊!!!

1,424

社区成员

发帖
与我相关
我的任务
社区描述
Swift,苹果于2014年WWDC(苹果开发者大会)发布的新开发语言,可与Objective-C共同运行于MAC OS和iOS平台,用于搭建基于苹果平台的应用程序。
swift 技术论坛(原bbs)
社区管理员
  • Swift
  • 网罗开发
  • 大熊猫侯佩
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧