iOS: Send multiple actions to a bar button

2019-09-03 10:45发布

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?

3条回答
你好瞎i
2楼-- · 2019-09-03 10:57

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.

查看更多
男人必须洒脱
3楼-- · 2019-09-03 11:09

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];
查看更多
一纸荒年 Trace。
4楼-- · 2019-09-03 11:10

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.

查看更多
登录 后发表回答