简体   繁体   中英

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. If i just create an instance of MainViewController and call the function it seems to loose its 'self' relevance.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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