fs_tigre fs_tigre - 4 months ago 30
iOS Question

Pass data back from a popover view controller on iPhone

How can I pass data back from a PopoverViewController to the main view controller on an iPhone?

I know I'm doing something terribly wrong but I cannot figure it out.

Here is the code:
PopoverViewController.swift

protocol PopoverViewControllerDelegate {
func messageData(data: AnyObject)
}

class PopoverViewController: UIViewController {
@IBOutlet weak var inputMessage: UITextField!
var delegate: PopoverViewControllerDelegate?

@IBAction func sendData(sender: AnyObject) {
if inputMessage.text != ""{
self.presentingViewController!.dismissViewControllerAnimated(true, completion: nil)
self.delegate?.messageData(inputMessage.text!)
}
}
}


Main ViewController.swift:

class ViewController: UIViewController, UIPopoverPresentationControllerDelegate, PopoverViewControllerDelegate {

@IBOutlet weak var showData: UILabel!

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// popover segue
if segue.identifier == "popoverSegue" {

let popoverViewController = segue.destinationViewController
popoverViewController.popoverPresentationController!.delegate = self
}
// code to comunicate with data in popoverViewController
let pvc = storyboard?.instantiateViewControllerWithIdentifier("popoverViewController") as! PopoverViewController
pvc.delegate = self
self.presentViewController(pvc, animated:false, completion:nil)
}

func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.None
}

func messageData(data: AnyObject) {
self.showData.text = "\(data)"
}
}


With the code above I can pass data back to the main view controller without a problem, the issue is that the popover doesn't work, it just acts like a regular
ViewController
occupying the whole screen.

The funny thing is that if I comment the following line of code the popover works but I can no longer pass data back, I can see the popover but the passing data stops working.

// if I comment this line
self.presentViewController(pvc, animated:false, completion:nil)


I don't get any errors, one just stops working.

Any suggestions?

Thanks a lot

Answer

In prepareForSegue, the destinationViewController is your PopoverViewController. You need to cast it to that and set the delegate on that so that you can pass back data, and you need to set the popoverPesentationController?.delegate as well. You don't need the rest of the code in prepareForSegue:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // popover segue
    if segue.identifier == "popoverSegue" {
        let popoverViewController = segue.destinationViewController as! PopoverViewController
        popoverViewController.delegate = self
        popoverViewController.popoverPresentationController?.delegate = self
    }
}
Comments