Brady Bess Brady Bess - 1 year ago 37
Swift Question

Protocol and Delegate Help? Value isn't passing back

I've got my

EditorViewController
that segues modally to my
ModalViewController
, and in the ModalViewController I have to pass some data back to the EditorViewController after the view is dismissed. I've looked at many tutorials about delegates and protocols, and I believe that's what I have to do to pass this information, but I can't seem to get the code right although I've followed the tutorials exactly. If anyone can see what's going wrong in here I would appreciate it. I'll post the code.

The protocol

protocol passColorBackDelegate {
func colorToChange(_ color: String)
}


The first view Controller

class EditorViewController: UIViewController, passColorBackDelegate {

func colorToChange(_ color: String) {
print("Hello")
}


The second view Controller file (the one with data to pass back to first), also has another class in it, I'm stingy with my files

class subView: UIView {

}

class ModalViewController: UIViewController {

var delegate: passColorBackDelegate?

@IBAction func changeColor(_ sender: UIButton) {
switch sender {
case blueColorButton: colorToChangeTo = "Blue"
case redColorButton: colorToChangeTo = "Red"
case greenColorButton: colorToChangeTo = "Green"
case purpColorButton: colorToChangeTo = "Purple"
default: print("error")
}
print(colorToChangeTo)
delegate?.colorToChange(colorToChangeTo)
self.dismiss(animated: true, completion: nil)
}


As you can see my protocol function doesn't include any of the data I need passed back yet, but the message still isn't printing, meaning the function isn't getting called. If anyone could tell me what I'm doing wrong I would appreciate it. Thanks

Answer Source

You will need to set the delegate before you perform the segue. Since it sounds like you're using Storyboards, this can be done in prepare(for segue):

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destinationVC = segue.destination as? ModalViewController {
        destinationVC.delegate = self
    }
}

Also, as Paul mentioned in the comments, capitalizing your protocols (PassColorBackProtocol) and classes (SubView) is the conventional style in Swift and helps other people understand your code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download