Search code examples
swiftios8popover

SWIFT: No idea how to get back the selected value from a popover to the calling controller


I just going crazy on Swift Popover “return” values. I am new to Objectiv-C as well as SWIFT but I try to focus on SWIFT.

I checked out tutorials around Google and StackOverflow about how to manage iOS popovers, learned a lot but the last peace I couldn’t make it. It is great so see how easy it is made using Swift and Xcode 6, love it, but I could not figure out how to get back the selected value from my popover to my calling view controller.

So here is my problem: (SIDENOTE: I am using SWIFT and do all using storyboard)

I have created a master ViewController with a button to select currencies. This button opens a “select currency” popover (linked to the CurrencyTableViewController (CTV) by CTRL-Dragging it to the CTV-Controller.

So far so good. The thing is, I have no idea how to get back the selected table row (currency) from the CTV-Table ;-( So I need the selected currency (table row) in the calling ViewController.

This is an excerpt from my ViewController (which is calling the popover)

class ViewController: UIViewController, UIPopoverPresentationControllerDelegate 
[...]
// This button is calling the popover
@IBAction func buttonCurrency(sender: AnyObject) {
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let controller = segue.destinationViewController as? CurrencyTableViewController {
controller.popoverPresentationController?.delegate = self
return
}
}
[...]

Hopefully somebody can help me with that missing last mile how to get back the selected row value back to my ViewController.

Thanks in advance

Cheers

John


Solution

  • I made quick example, hope it helps:

    // This is you popover's class
    
    @objc protocol CurrencySelectedDelegate {
        func currencySelected(currName: String)
    }
    
    class MyPopOverController: UIViewController {
    
    
        weak var delegate: CurrencySelectedDelegate?
    
    
        @IBAction func readyButtonPressed(sender: AnyObject) {
    
        // Do what you want
    
        delegate?.currencySelected("Euro/Dollar etc....")
    
        // close popover
        }
    }
    
    // ViewController
    class ViewController: UIViewController, CurrencySelectedDelegate {
    
        override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
            if segue.identifier == "mySegue" { // your identifier here
                let controller = segue.destinationViewController as! MyPopOverController
                controller.delegate = self
            }
        }
    
    }
    

    And remember just declare that currencySelected function in your ViewController.