简体   繁体   English

iOS Swift-使用容器视图在视图控制器之间传递数据

[英]IOS Swift - Passing data between view controllers using container view

I am a little confused on how to use container views correctly, i will try to explain it the best i can. 对于如何正确使用容器视图,我有些困惑,我将尽我所能解释。

I have a main view controller that has an animation function. 我有一个具有动画功能的主视图控制器。

import UIKit

class MainViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate {

// Run view setups
override func viewDidLoad() {
    super.viewDidLoad()
}

func closePicker(){
    self.view.layoutIfNeeded();
    UIView.animateWithDuration(0.5, animations: {
            self.countryPickerConst.constant = -206;
        self.view.layoutIfNeeded();
    })
} 

}

In interface builder i have added a container view with a new view controller that contains a button like so: 在界面构建器中,我添加了带有新视图控制器的容器视图,其中包含如下所示的按钮:

import UIKit

class ContainerViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

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



@IBAction func runAnimation(sender: UIButton) {

    //I want to call the function in my other view controller

}


}

In the action runAnimation i want to call the function in the MainViewController. 在动作runAnimation中,我想在MainViewController中调用该函数。 If i just create an instance of MainViewController and call the function it seems to loose its 'self' relevance. 如果我只是创建MainViewController的实例并调用该函数,则它似乎失去了“自我”的相关性。

If someone could explain to me the best practice for doing things like this that would be great. 如果有人可以向我解释这样做的最佳实践,那将是很好的。

Thanks 谢谢

From your explanation MainViewController is the parent of ContainerViewController so to access closePicker from ContainerViewController you would do: 根据您的解释, MainViewControllerContainerViewController的父级,因此您可以从ContainerViewController访问closePicker

@IBAction func runAnimation(sender: UIButton) {
  (self.parentViewController as! MainViewController).closePicker()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM