loup4 loup4 - 6 months ago 13
Swift Question

How can I run delegated method inside IBAction?

I have some methods in second view controller. I access them through delegate - inside func buttonSender. Main goal is to pass currentTitle of a button as an argument to a viewController.addNewMessage. What is the best way to do this?

ChatViewController:

protocol ReactToButtons {
func buttonSender(viewController: MyChatViewController)
}


class MyChatViewController: ChatViewController{

var delegate: ReactToButtons?

override func viewDidLoad() {
super.viewDidLoad()
delegate!.buttonSender(self)

}
}


ContainerViewController:

class ContainerViewController: UIViewController, ReactToButtons {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let myVC = segue.destinationViewController as! MyChatViewController
myVC.delegate = self
}

func buttonSender(viewController: MyChatViewController) {
viewController.addNewMessage(/*HERE GOES CURRENT TITLE*/)
}

@IBAction func leftButtonPressed(sender: AnyObject) {
let currentTitle = sender.currentTitle!

}

Answer

I have change my answer to suit your code

class ContainerViewController: UIViewController, ReactToButtons {
    var delegate: MyChatViewController!
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        let myVC = segue.destinationViewController as! MyChatViewController
        myVC.delegate = self
    }

    func buttonSender(viewController: MyChatViewController) {
    delegate = viewController
    }

    @IBAction func leftButtonPressed(sender: AnyObject) {
        let currentTitle = sender.currentTitle!
        delegate!.addNewMessage(currentTitle)
    }
}