Marin Marin - 6 days ago 5
Swift Question

Access viewcontroller from button

I have ButtonClass which has buttonTapped method implemented.

The button itself is on the view. I need to add an extra layer when the button is pressed but I don't have access to self in the ButtonClass because self is a button not the view... Basically I need to access self.view found in the viewController but that's another class. If I create an new instance like so viewController() it won't help because it wont' be the same instance.

Answer

If you're adding the buttonTapped method from the custom button class then you need to create a delegate, and call the delegate method when the user the buttonTapped method is called.

In your custom button class

protocol YourCustomButtonDelegate {
    func changeSomethingInTheView()
}

class YourCustomButtonClass {

    var delegate: YourCustomButtonDelegate?

    func buttonTapped(_ sender: AnyObject) {
        if let delegate = delegate {
            delegate.changeSomethingInTheView()
        }
    }
}

And in the ViewController

class ViewController: UIViewController, CustomCellDelegate {

    @IBOutlet weak var button: YourCustomButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        button.delegate = self
    }

    func changeSomethingInTheView() {
        // write your code here...
    }
}
Comments