如何使用swift 3

时间:2016-08-11 06:16:54

标签: ios swift3

我正在使用instantiateViewControllerWithIdentifier(identifier: String)函数从ViewControllerA创建ViewControllerB的实例。

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("vcB") as VCB;
rootController!.presentViewController(vc, animated: true, completion: nil)


class VCB: UIViewController {

required init?(coder aDecoder: NSCoder){
    super.init(coder: aDecoder)
  }

}

我想访问我在ViewControllerB中传递的值,如何实现这一目标。

我已经完成了 Passing Data between View Controllers链接,但目标c。

中的答案

3 个答案:

答案 0 :(得分:3)

您可以尝试

import UIKit
class ViewControllerA: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func passDataAction(sender: AnyObject) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewControllerWithIdentifier("UIViewControllerB") as! ViewControllerB;
    vc.dataFromOtherView = "The data is passed"
    self.presentViewController(vc, animated: true, completion: nil)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

另一个班级

import UIKit
class ViewControllerB: UIViewController {

var dataFromOtherView: String = ""

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    print(dataFromOtherView)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

答案 1 :(得分:2)

您可以在var viewController中声明VCB并将数据注入此属性

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("vcB") as VCB;

vc.yourData = SOME_DATA

rootController!.presentViewController(vc, animated: true, completion: nil)


class VCB: UIViewController {

var yourData: AnyObject?

required init?(coder aDecoder: NSCoder){
    super.init(coder: aDecoder)
  }

}

答案 2 :(得分:1)

只需使用此代码即可将数据从一个视图控制器发送到另一个视图控制器

   let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc=storyboard.instantiateViewControllerWithIdentifier("secondView") as! ViewControllerB;
vc.dataFromOtherView = "The data is passed"
self.presentViewController(vc, animated: true, completion: nil)