In my app I'm looking to customise a bar button that currently shows the user's location so that if the user taps and holds down it shows a subview with some other info. However it seems I can only send one action. Is this definitely the case or is there a way I can have more than one action? I know there's a subclass to enable the user orientation position (like in the Maps app) - could I somehow implement similar functionality?
问题:
回答1:
UIBarButtonItems only send one event. You'll need to create your own custom control, add Gesture Recognizers to it to recognize tap and long press, and create a bar button item with your custom control.
回答2:
Create your own UIButton
and add all the gesture recognizers or actions you want. Then create the UIBarButtonItem
with initWithCustomView:
.
UIButton *btn = // create button as needed
btn.showsTouchWhenHighlighted = YES; // keep the "glow" effect
[btn addTarget:self action:@selector(someSelector) forControlEvents:someEvent];
// repeat as needed for different events/selectors
// or add gesture recognizers
UIBarButtonItem *btnItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
回答3:
As the other comments say: It is not possible to add a "Long Press" gesture recognizer to the native bar button. There are two ways you could go about this:
1) Find the UIView that represents the button in the view hierarchy and add a gesture recognizer to it. More info here. This is is pretty straight forward and done with a few lines of code but might break in case internal structuring of the views change in the future.
2) Set a customView for the navigation bar button by dragging a UIButton onto it (Interfacebuilder) or setting the customView property programmatically. You then need to give that UIButton the appearance of a navBarButton and add a gesture recognizer to it.