简体   繁体   中英

Custom UIButton class with same action for different ViewControllers

I've seen a lot of examples of creating buttons programmatically in ViewController class and in storyboards (using @IBAction after that).

Is there a way to create a custom class for a button and to make it toggle my side menu without rewriting this action in every single ViewController.

Now I create this button on each VC I need in storyboard and copy-paste this code:

@IBAction func openMenuClick() {
    sideMenuController?.toggle()
}

How can I avoid this code duplication?

If this button is in every view controller in storyboard then I guess you need to connect it at some point.

I suggest you create a subclass of UIViewController which is then a base class for all your view controllers with this button. You should create an outlet in base class which should then be connected in storyboard for each of the subclasses.

Then only the base class has this method you posted and on view did load you need to add a target manually to this method. I guess alternatively if the base view controller has this method as IBAction you could simply connect that one in your storyboard.

In storyboard you have to create the button on navigation bar for every View Controller, now for the action of the menu button you can create an IBAction like

extension UIViewController {

@IBAction func btnActionBack(_ sender: UIButton) {
   moveBack()
}

@IBAction func btnActionOpenSideMenu(_ sender: UIButton) {
    toggleSideMenuView()
} }

You can now drag the touchUpInside outlet of button to the IBAction btnActionOpenSideMenu . I have used this for myself, also i have created a universal back button action to pop view controller

Create a common class for button there you can add:

button.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)


func buttonAction(sender: UIButton!) {   print("Button tapped") }

In your button class;

Swift 4:

open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesEnded(touches, with: event)
    guard let touchPoint = touches.first?.location(in: self) else { return }
    guard self.bounds.contains(touchPoint) else { return }

    // Do what you wanna do here

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM