问题
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.
回答1:
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:
Now you can connect your send feedback button outlet and action:
回答2:
Use extension of UIViewController.
extension UIViewController {
func sendFeedBack() {
//write your code here
}
}
And call from any ViewController.
来源:https://stackoverflow.com/questions/44766596/same-button-across-all-view-controllers-in-ios-app