iosswiftswift3uibuttonviewcontroller

Same button across all view controllers in ios app


I am developing an app with 10 view controllers, including 2 webview controllers. Every view controller contains a 'send feedback' button on top right with exactly same style and functionality. Right now, I am writing exact same code in each view controller for the buttons. I was wondering if there is a way to write the method only at one place and use it for all the buttons, since the function is same. I am using swift 3.


Solution

  • Create new subclass of view controller:

    class SendFeedbackViewController: UIViewController {
        @IBOutlet weak var sendFeedbackButton: UIButton!
    
        @IBAction func sendFeedback() {
            /* do whatever you need */
        }
    }
    

    Then subclass all your view controllers from this new view controller:

    class YourViewController: SendFeedbackViewController {
        /* your entire logic */
    }
    

    In storyboard set class type: enter image description here

    Now you can connect your send feedback button outlet and action: enter image description here enter image description here