Search code examples
iosswiftuibuttonswrevealviewcontrolleruibuttonbaritem

SWReveal with a UIButton


So I wanted to add a slide menu to my app where if you tap a button, the menu slides from the left. After some research I found a guide for using SWRevealViewController to create a slide out menu, but I quickly realized that video, and pretty much every other guide for SWReveal, uses a UIBarButtonItem for the button that you tap to reveal the menu. So what I need help with is figuring out how to do what the guide says to do for the UIBarButtonItem, but for a UIButton instead.

Let's say there is a UIBarButtonItem called OpenSideBar. The guide says to do this in the viewDidLoad method:

OpenSideBar.target = self.revealViewController()
OpenSideBar.action = Selector("revealToggle")

So I'm not exactly sure what that does but I need to find a way to do it for a UIButton. An explanation for what it does would also be appreciated because the guy in the video didn't do much explaining.

The button is currently an outlet:

@IBOutlet weak var OpenSideBar: UIButton!

but please specify if I should recreate it as an action instead and do stuff in the function instead of the viewDidLoad method. Thanks in advance.

P.S. The SWViewController.h file can be found on github at this link:

https://github.com/PCmex/lift-side-memu-in-swift-3/blob/master/memuDemo/SWRevealViewController.h

and SWViewController.m at this link:

https://github.com/PCmex/lift-side-memu-in-swift-3/blob/master/memuDemo/SWRevealViewController.m


Solution

  • The line OpenSideBar.target = self.revealViewController() sets the target for your UIBarButtonItem and the line OpenSideBar.action = Selector("revealToggle") sets the action that needs to be performed upon tapping the said button.

    You can achieve this functionality using UIButton in one of two ways. You can either set the target action for a UIButton just like you would for a `UIBarButtonItem. The only difference is that they both have a different syntax. You would be doing it like this

    OpenSideBar.addTarget(self.revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:)), for: .touchUpInside)
    

    or you can hookup your @IBAction and in your method, use

    self.revealViewController().revealToggle(self)