iOS: Send multiple actions to a bar button

﹥>﹥吖頭↗ 提交于 2019-12-11 17:51:31

问题


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.



来源:https://stackoverflow.com/questions/13828990/ios-send-multiple-actions-to-a-bar-button

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