Implementing SWRevealViewController in Swift

Prateek picture Prateek · Jul 11, 2014 · Viewed 8.7k times · Source

I am using the 'plugin' SWRevealViewController to help produce a sidebar in my app. Now in objective-C, you can control the side bar using the following code:

[self.sidebarButton setTarget: self.revealViewController];
        [self.sidebarButton setAction: @selector( revealToggle: )];
        [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];

Where sidebarButton has been hooked up UIBarButtonItem and IBOutlet. Now I am trying to apply this to my Swift code and I have mixed success.

I've set an @IBOutlet var button. Now I've tried both UIBarButtonItem and UIButton. When I try UIBarButtonItem, I have used the following line:

button = UIBarButtonItem(barButtonSystemItem: .Add, target: self.revealViewController(), action: "revealToggle:")

However, this does nothing and the button doesn't function. However, if I set button to be a UIButton and hook this up with the following:

button.addTarget(self.revealViewController(), action:"revealToggle:", forControlEvents:UIControlEvents.TouchUpInside)

This works to slide the bar out and in but not via gestures. The issue is that I can't add a UIButton to the toolbar (in StoryBoard anyway).

So is there any way to implement this properly? Additionally, is it possible to add the gesture recogniser as well?

Thanks

EDIT

Okay I've managed to get the gesture toggle working, although I think my method is a bit long winded:

var swipeRight = UISwipeGestureRecognizer(target: self.revealViewController(), action: "revealToggle:")
    swipeRight.direction = UISwipeGestureRecognizerDirection.Right
    self.view.addGestureRecognizer(swipeRight)

    var swipeLeft = UISwipeGestureRecognizer(target: self.revealViewController(), action: "revealToggle:")
    swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
    self.view.addGestureRecognizer(swipeLeft)

So please correct.

Answer

Emi picture Emi · Dec 10, 2014

for the UIBarButtonItem this works

@IBOutlet weak var sideButton: UIBarButtonItem!

@IBAction func sideButtonPress(sender: UIBarButtonItem) {
       revealViewController().revealToggle(sender)
}