Same button across all view controllers in ios app

2019-07-09 23:58发布

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.

2条回答
▲ chillily
2楼-- · 2019-07-10 00:00

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

查看更多
放我归山
3楼-- · 2019-07-10 00:07

Use extension of UIViewController.

extension UIViewController {
   func sendFeedBack() {
     //write your code here
   }
}

And call from any ViewController.

查看更多
登录 后发表回答