Paul Crono
Paul Crono

Reputation: 61

Custom UIBackButtonItem and UINavigationController gestures

I need to have a UINavigationBar with custom UIBarButtonItem.

I know how to do it (with custom view), but there is one problem:

Using the default back button item gives us the iOS 7 gestures, so we can swipe to go back etc., using custom UIBarButtonItem item doesn't give us these gestures.

How can we create custom UIBarButtonItem and maintain the iOS 7 gestures ?

I dont want to build whole swipe gesture from beginning, I don't believe that it is the only way.

Upvotes: 1

Views: 207

Answers (2)

deej
deej

Reputation: 1768

You can use a little trick to get the native gesture working. Create a subclass of UINavigationItem, then override leftBarButtonItems method:

- (NSArray*)leftBarButtonItems
{
    return nil;
}

Now use this class for the item that has custom left UIBarButtonItem. The gesture works! This is because UINavigationController thinks there are no left items and enables the gesture. You are still able to access your custom item through the leftBarButtonItem property.

Upvotes: 0

JackyJohnson
JackyJohnson

Reputation: 3126

Gestures can be basically be added to any UIView using the addGesture:(UIGestureRecognizer *)gesture method.

Basically, you need to instantiate a UISwipeGestureRecognizer object, set whatever properties you want and implement its delegate. Then, simply add it to the view on which you wish the UISwipeGestureRecognizer to be recognized.

So for instance, since UINavigationBar inherits from UIView, you can send the addGesture:(UIGestureRecognizer *)gesture message to it like so:

UINavigationBar *myNavigationBar = [UINavigationBar new];
[self.view addView:myNavigationBar]; // 'self' refers to your view controller assuming this is where your code lives
UISwipeGestureRecognizer *swipeGesture = [UISwipeGestureRecognizer new]; // use the designated initializer method instead
[myNavigationBar addGesture:swipeGesture]; // again, this method is inherited from UIView, it's how you add gestures to views
[myNavigationBar setUserInteractionEnabled:YES]; // this is very important for enabling gestures

There you go.

Keep in mind this is kind of half the work because you want to implement animation to make it look like you're swiping a page and it moves as you are swiping.

Upvotes: 1

Related Questions