Search code examples
iosswiftuiviewcontrolleruicontainerview

Swift - access UIButton inside ContainerView in another ViewController


I am having a problem accessing my UIButton that's inside a ContainerView from another ViewController.

If the user taps the button a SubView should appear inside of my ViewController. I tried dragging the button in my ViewController file to create an @IBAaction func tapped() but that is not working.

It only works inside of the ContainerView.swift file. But I can not create my Subview there...

I hope you get my problem, I am grateful for every help!

enter image description here

import UIKit

class ContainerViewController: UIViewController {




    override func viewDidLoad() {
        super.viewDidLoad()


        // Do any additional setup after loading the view.
    }


    @IBAction func addButtonTapped(_ sender: Any) {
        print("add Button")         
}

Solution

  • You can achieve this using NotificationCenter and Delegates. Here is how you can achieve it with NotificationCenter

    In your ContainerViewController you can post notification on button click

    @IBAction func yourBtnTap(sender : UIButton) { 
    NotificationCenter.default.post(name: Notification.Name("myBtnTapped"), object: nil)
    } 
    

    In your CurrentViewController you have to first register to receive this notification. So in your viewDidLoad, do this:

    NotificationCenter.default.addObserver(self, selector: #selector(self.myBtnTappedAction(notification:)), name: Notification.Name("myBtnTapped"), object: nil)
    

    Now in your CurrentViewContoller create myBtnTappedAction function that will be called whenever the button is tapped.

    @objc func myBtnTappedAction(notification : Notification) { 
    // now you can perform all your actions here. this function will be called everytime the button in the container view is tapped.
    }