Custom UIBackButtonItem and UINavigationController gestures

僤鯓⒐⒋嵵緔 提交于 2019-12-14 02:35:08

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/23066088/custom-uibackbuttonitem-and-uinavigationcontroller-gestures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!