/ Software

Swift: Invoking Caller's Method with Protocols

One line problem/solution: using [Protocols](swift protocol optional) when delegating calls to the caller class from a Factory.

I have a Button Factory (ButtonFactory.swift) which gives the user an instance of UIButton in a simple grid view (GridView.swift), which will invoke a method on the main class that calls the factory. A quick & simple solution to this would be like:

- ButtonFactory.swift
protocol ButtonDelegate {
    func buttonPressed(button:UIButton)
}

class ButtonFactory {
    var delegate:ButtonDelegate!

    func create(...) -> UIButton {
        let button = CustomButton()

        button.addTarget(self, action: "actionPressed:", forControlEvents: .TouchUpInside)

        return button
    }

    func actionPressed(sender: UIButton!) {
        print("actionPressed ButtonFactory")
        delegate.buttonPressed(sender)
    }
}
- GridView.swift
class GridView: UIViewController, ButtonDelegate {

    func createButton() {
        let factory = ButtonFactory()
        factory.delegate = self
        let button = factory.create(...)
        self.view.addSubview(button)
    }

    func buttonPressed(button:UIButton) {
        print ("buttonPressed GridView")
        // actions here
    }
}
Koray Alkan

Koray Alkan

Software Developer @Bloomberg. Love classical music, reading and playing the trumpet. Opinions are my own.

Read More