如何在不使用segues的情况下将数据从一个viewController传递到另一个viewController?

时间:2018-04-28 17:11:05

标签: ios swift viewcontroller

在我的第一个ViewController中:

var storyboard = UIStoryboard(name: "Main", bundle: nil)
var controller = storyboard.instantiateViewController(withIdentifier: "backGroundController") as! BackGroundWithContainer
delegate?.myFunction(float: floatItryToPass)

在我的第二个VC中:

let whiteView = UIView()
@IBOutlet var TopBarView: UIView!

func takeScrollUpFloat(float: CGFloat) {

    print("scrollUpFloatTaker: ", float) //works fine
    whiteView.center.y = view.frame.height //bad access error here
    TopBarView.center.y = view.frame.height //found nil error here
}

难度实际上是改变第二个ViewController中定义的值。如何在不实际调用segue的情况下解决这个问题?我知道在打开视图时有很多方法可以做到,但我必须解决它WITOUT再次加载第二个视图。第二个视图目前正在运行。

1 个答案:

答案 0 :(得分:0)

以下是如何解决它

var storyboard = UIStoryboard(name: "Main", bundle: nil)
var secondController = storyboard.instantiateViewController(withIdentifier: "backGroundController") as! BackGroundWithContainer
secondController.passedFloat = floatItryToPass

现在在你的第二个视图控制器

var passedFloat: CGFloat!
let whiteView = UIView()
@IBOutlet var TopBarView: UIView!

override func viewDidLoad() {

    print("scrollUpFloatTaker: ", float) //works fine
    // no bad access error here since your view is loaded, i.e viewDidLoad
    whiteView.center.y = view.frame.height 
    // all your IBOutlet variables also get values by the time viewDidLoad
    // is called, so you won't be getting nil for your TopBarView
    TopBarView.center.y = view.frame.height //found nil error here
}

第一个