Disabling dictation within the app [duplicate] - objective-c

Ours is a health care app. We have a HIPAA-compliant speech recognizer in the app through which all the dictation can take place. The hospitals don't want physicians to accidentally start speaking to the Nuance Dragon server which is not HIPAA-compliant. So, I was looking for ways I could supress the dictation key on the keyboard.
I tried putting a fake button on the Dictation button on the key pad, but on the iPad the split dock concept keeps moving the microphone all over the screen. This does not sound like a reasonable solution. Are there any experts out there who could help me?

OKAY, finally got it! The trick is to observe UITextInputMode change notifications, and then to gather the identifier of the changed mode (Code seems to avoid the direct use of Private API, though seems to require a little knowledge of private API in general), and when the mode changes to dictation, resignFirstResponder (which will cancel the voice dictation). YAY! Here is some code:
Somewhere in your app delegate (at least that's where I put it)
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(inputModeDidChange:) name:#"UITextInputCurrentInputModeDidChangeNotification"
object:nil];
And then you can
UIView *resignFirstResponder(UIView *theView)
{
if([theView isFirstResponder])
{
[theView resignFirstResponder];
return theView;
}
for(UIView *subview in theView.subviews)
{
UIView *result = resignFirstResponder(subview);
if(result) return result;
}
return nil;
}
- (void)inputModeDidChange:(NSNotification *)notification
{
// Allows us to block dictation
UITextInputMode *inputMode = [UITextInputMode currentInputMode];
NSString *modeIdentifier = [inputMode respondsToSelector:#selector(identifier)] ? (NSString *)[inputMode performSelector:#selector(identifier)] : nil;
if([modeIdentifier isEqualToString:#"dictation"])
{
[UIView setAnimationsEnabled:NO];
UIView *resigned = resignFirstResponder(window);
[resigned becomeFirstResponder];
[UIView setAnimationsEnabled:YES];
UIAlertView *denyAlert = [[[UIAlertView alloc] initWithTitle:#"Denied" message:nil delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles:nil] autorelease];
[denyAlert show];
}
}

you can create your own keyboard and set the inputView for the text fields that will accept this dictation. then when they press any keys they will get your keyboard, therefore you dont have to override the keys on the standard keyboard, you will be able to customize the entire thing.
self.myButton.inputView = self.customKeyboardView;
here is an example of an extremely custom keyboard
http://blog.carbonfive.com/2012/03/12/customizing-the-ios-keyboard/
Ray also has a teriffic tutorial on custom keyboards.
http://www.raywenderlich.com/1063/ipad-for-iphone-developers-101-custom-input-view-tutorial
I hope that helps.

I had the same issue and the only way i found that hides the dictation button is changing the keyboard type.
For me changing it to email type seemed to be reasonable:
textField.keyboardType = UIKeyboardTypeEmailAddress;

You could make a subclass of UITextField/UITextView that overrides insertDictationResult: to not insert anything.
This won't prevent the information being sent, but you could then display an alert informing them of the breech.

This is a Swift 4 solution based on #BadPirate's hack. It will trigger the initial bell sound stating that dictation started, but the dictation layout will never appear on the keyboard.
This will not hide the dictation button from your keyboard: for that the only option seems to be to use an email layout with UIKeyboardType.emailAddress.
In viewDidLoad of the view controller owning the UITextField for which you want to disable dictation:
// Track if the keyboard mode changed to discard dictation
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardModeChanged),
name: UITextInputMode.currentInputModeDidChangeNotification,
object: nil)
Then the custom callback:
#objc func keyboardModeChanged(notification: Notification) {
// Could use `Selector("identifier")` instead for idSelector but
// it would trigger a warning advising to use #selector instead
let idSelector = #selector(getter: UILayoutGuide.identifier)
// Check if the text input mode is dictation
guard
let textField = yourTextField as? UITextField
let mode = textField.textInputMode,
mode.responds(to: idSelector),
let id = mode.perform(idSelector)?.takeUnretainedValue() as? String,
id.contains("dictation") else {
return
}
// If the keyboard is in dictation mode, hide
// then show the keyboard without animations
// to display the initial generic keyboard
UIView.setAnimationsEnabled(false)
textField.resignFirstResponder()
textField.becomeFirstResponder()
UIView.setAnimationsEnabled(true)
// Do additional update here to inform your
// user that dictation is disabled
}

Related

How to listen to Apple TV Remote in Objective-C?

This seems like it should be pretty straight-forward but I'm having trouble finding a working example, good documentation, or even many StackOverflow posts that are helpful.
I have a custom view which contains an AVPlayer, like so:
#implementation
{
#private
AVPlayerViewController *controller
}
- (id) init
{
self = [super init];
if (self)
{
controller = [[AVPlayerViewController alloc] init];
controller.view.frame = self.view.bounds;
[self.view addSubview:controller.view];
}
return self;
}
#end
(I have a few other views like a message that overlays the player, a poster that I display while swapping videos, etc - but this is the basic setup)
When I integrated the IMA SDK, I started to have issues. If you press the pause button on the remote control during an ad, it pauses the ad just fine. But if you press the pause button again it doesn't unpause the ad, but instead unpauses my content player behind the ad. I don't hear any audio, but I know the content player was unpaused because I have ID3 metadata in my video and an NSLog() statement when I hit it, and I begin to see these logs. If I press the pause button again, the logs pause. I press it a fourth time, the logs start up again.
To try and fix this I wanted to bind a listener to the remote's play/pause button and make sure that if I was playing an ad then the ad was resumed, not the content. So I tried adding the following to my init method on my view:
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self.view action:#selector(tapped:)];
[tapRecognizer setAllowedPressTypes:#[ [NSNumber numberWithInt:UIPressTypePlayPause] ]];
[self.view addGestureRecognizer:tapRecognizer];
I then created the following method:
- (void) tapped: (UITapGestureRecognizer *) sender
{
NSLog(#"Tapped");
}
This isn't being called. I'm pretty confident I made a simple mistake, but the documentation isn't very clear, so I'm not sure what I should be doing instead. The official documentation on detecting button presses uses Swift and says:
let tapRecognizer = UITapGestureRecognizer(target: self, action: "tapped:")
tapRecognizer.allowedPressTypes = [NSNumber(integer: UIPressType.PlayPause.rawValue)];
self.view.addGestureRecognizer(tapRecognizer)
I believe I translated those three lines well. The documentation then doesn't show what the tapped method should look like, but instead goes on a tangent about working with low-level event handling. So to get the appropriate method signature I looked at the documentation on UITagGestureRecognizer which had the following (Swift) example for writing a handler:
func handleTap(sender: UITapGestureRecognizer) {
if sender.state == .ended {
// handling code
}
}
This is why I went with - (void) tapped: (UITapGestureRecognizer *) sender
Still, after all of that, it's not working.
Quick Update
I tried replacing:
initWithTarget:self.view
With:
initWithTarget:controller.view
And:
self.view addGestureRecognizer
With:
controller.view addGestureRecognizer
And this time it looks like something actually happened when I pressed the play/pause button. The app crashed and Xcode gave me the following error:
2019-12-17 12:16:50.937007-0500 Example tvOS App[381:48776] -[_AVPlayerViewControllerContainerView tapped:]: unrecognized selector sent to instance 0x10194e060
So it seems like (correct me if I'm wrong):
The AVPlayerViewController has the focus, not my view
The gesture recognizer calls the selector on whatever class you register it to, rather than the class that did the registering
So I guess an alternative question to my original would be: How do I allow my class to handle a gesture on some other class (e.g. AVPlayerViewController)?
The target does not need to equal the view that the gesture recognizer is attached to. You can set the target to MyView but still attach the gesture recognizer to controller.view
To work around the unrecognized selector crash, you need to make sure you're providing the correct object as the target for your gesture recognizer. The way UIGestureRecognizer works is that when the gesture is recognized, it will invoke the given selector on the given target object. In other words, when gesture fires, it's going to perform the equivalent of:
[target selector:self];
(You seem to be treating the target as the view that the gesture will be attached to, which isn't how it works)
So if you implemented tapped: on your class MyView, then the target you pass to the gesture recognizer initializer should be an instance of MyView. You probably want to provide self, not self.view.

Double-click action for menu bar icon in Mac OSX

I'm writing a small Mac OSX app that displays a menu bar icon. When clicked, a menu pops up.
I'd like to have a "default" action for the menu bar icon. Basically, to execute an action when double-clicking it, without having to select the action from the menu.
I looked over the Apple docs and there's is such a thing in NSStatusItem called doubleAction, but it's soft deprecated and does not (seem to) work. More over, the docs it says to use the button property, but trying to do so results in the compiler error shown below:
Any code or guidance are much appreciated, thanks!
The situation as it stands today (Xcode 7.3.1, OSX 10.11.4):
the doubleAction of NSStatusItem is deprecated (and NOT actually working).
Apple tells you to use the button property - but there's no header for doubleAction (I wonder if the implementation exists). Oh, it's also read-only.
there are no other options regarding left/right/double click in any of the NSStatusItem's properties.
The workaround: create a category for NSButton (the exact same that Apple was talking about) and implement a custom click handler that posts a notification when a double click was detected, like the following:
#implementation NSButton (CustomClick)
- (void)mouseDown:(NSEvent *)event {
if (self.tag != kActivateCustomClick) {
[super mouseDown:event];
return;
}
switch (event.clickCount) {
case 1: {
[self performSelector:#selector(callMouseDownSuper:) withObject:event afterDelay:[NSEvent doubleClickInterval]];
break;
}
case 2: {
[NSRunLoop cancelPreviousPerformRequestsWithTarget:self];
[[NSNotificationCenter defaultCenter] postNotificationName:#"double_click_event" object:nil];
break;
}
}
}
- (void)callMouseDownSuper:(NSEvent *)event {
[super mouseDown:event];
}
#end
As you can see, this handler only handles NSButton instances that have a specific tag value.
When a click is detected, I defer the call to super for handling by the system's double-click interval. If within that time I receive another click, I cancel the call to super and treat it as a double-click.
Hope it helps!
You can use NSApp.currentEvent
self.statusItem.button.target = self;
self.statusItem.button.action = #selector(clickOnStatusItem:);
...
- (void)clickOnStatusItem:(id)sender {
if (NSApp.currentEvent.clickCount == 2) {
// Double click on status item
}
}
also, you can process a right mouse button on the status bar item

How to send app to background

On tvOS, I've only been able to get the begin states of button presses from the Siri remote by overriding the pressesBegan method on the view. If I use gesture recognizers, it only returns the end state. The catch is, when I override pressesBegan, even if I only use it for the select button, it still overrides the default function of the menu button (to push the app to the background). So I was looking into how to send the app to the background and call that method for the menu button (as is default behavior), but it appears that it is not kosher per Apple's standards to do that.
Here is my code for reference:
-(void)pressesBegan:(NSSet<UIPress *> *)presses withEvent:(UIPressesEvent *)event {
for (UIPress* press in presses) {
switch (press.type) {
case UIPressTypeSelect:
NSLog(#"press began");
break;
case UIPressTypeMenu:
// this is where I would call the send to background call if Apple would allow that
// removing this case also has no effect on what happens
break;
default:
break;
}
}
As an alternative, this ONLY sends button release signals, but nothing presses begin.
UITapGestureRecognizer* tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(gestureTap:)];
tapGesture.allowedPressTypes = #[[NSNumber numberWithInteger:UIPressTypeSelect]];
[view addGestureRecognizer:tapGesture];
When there's some behavior that happens if you don't override a method, and the behavior goes away in an empty override implementation, it stands to reason that behavior is provided by the superclass. (Cocoa is dynamic and complicated, so such inferences aren't true 100% of the time, but often enough.)
So, just call super for the cases where you don't want your override to change the default behavior:
case UIPressTypeMenu:
[super pressesBegan: presses withEvent: event];
break;

Suspending keyboard when user press on home button?

I am developing an application were everything is working fine, except one i.e. when user press on home while keyboard is in active and again opens my application the view frame bounds are changing and moving out of bounds. My expected result is keyboard should get suspended or the view should stay in the same position when it is come back from background to foreground with keyboard in-active state.
I hope people understand my scenario and reply ASAP.
Thanks.
I have found the solution to my question, i hope people can use my solution. Below is the code what I have done,
Add the below line of code in your RootViewController file (i.e. which view is coming at first when you open your APP).
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(receivedNotification:) name:UIApplicationDidEnterBackgroundNotification object:nil];
And then add a private method as below
- (void) receivedNotification:(NSNotification *) notification
{
if ([username isFirstResponder])
{
[username resignFirstResponder];
}
else if ([password isFirstResponder])
{
[password resignFirstResponder];
}
}
I hope it help some body,Thank u.
Further assistance please see the mentioned link,
there is a method in the app delegate
- (void)applicationDidEnterBackground:(UIApplication *)application
this method is fired when you press the home button.
do the necessary changes(textField resignFirstResponder) in this method and it should work fine i guess.
EDIT here's the code
in the class where you have your textfield create a method
-(void)performWhenHomeBtnprssed
{
[MytextField resignFirstResponder];
}
then in
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[myClassObj performWhenHomeBtnprssed];
}
also i agree with #valexa you should find the root cause of the problem
In software development it is always better to address the root causes than to patch the effect, in your case there are problems with the positioning of your views and you should address that, foreground/background cycling should not affect the views positioning.

How can you add a UIGestureRecognizer to a UIBarButtonItem as in the common undo/redo UIPopoverController scheme on iPad apps?

Problem
In my iPad app, I cannot attach a popover to a button bar item only after press-and-hold events. But this seems to be standard for undo/redo. How do other apps do this?
Background
I have an undo button (UIBarButtonSystemItemUndo) in the toolbar of my UIKit (iPad) app. When I press the undo button, it fires it's action which is undo:, and that executes correctly.
However, the "standard UE convention" for undo/redo on iPad is that pressing undo executes an undo but pressing and holding the button reveals a popover controller where the user selected either "undo" or "redo" until the controller is dismissed.
The normal way to attach a popover controller is with presentPopoverFromBarButtonItem:, and I can configure this easily enough. To get this to show only after press-and-hold we have to set a view to respond to "long press" gesture events as in this snippet:
UILongPressGestureRecognizer *longPressOnUndoGesture = [[UILongPressGestureRecognizer alloc]
initWithTarget:self
action:#selector(handleLongPressOnUndoGesture:)];
//Broken because there is no customView in a UIBarButtonSystemItemUndo item
[self.undoButtonItem.customView addGestureRecognizer:longPressOnUndoGesture];
[longPressOnUndoGesture release];
With this, after a press-and-hold on the view the method handleLongPressOnUndoGesture: will get called, and within this method I will configure and display the popover for undo/redo. So far, so good.
The problem with this is that there is no view to attach to. self.undoButtonItem is a UIButtonBarItem, not a view.
Possible solutions
1) [The ideal] Attach the gesture recognizer to the button bar item. It is possible to attach a gesture recognizer to a view, but UIButtonBarItem is not a view. It does have a property for .customView, but that property is nil when the buttonbaritem is a standard system type (in this case it is).
2) Use another view. I could use the UIToolbar but that would require some weird hit-testing and be an all around hack, if even possible in the first place. There is no other alternative view to use that I can think of.
3) Use the customView property. Standard types like UIBarButtonSystemItemUndo have no customView (it is nil). Setting the customView will erase the standard contents which it needs to have. This would amount to re-implementing all the look and function of UIBarButtonSystemItemUndo, again if even possible to do.
Question
How can I attach a gesture recognizer to this "button"? More specifically, how can I implement the standard press-and-hold-to-show-redo-popover in an iPad app?
Ideas? Thank you very much, especially if someone actually has this working in their app (I'm thinking of you, omni) and wants to share...
Note: this no longer works as of iOS 11
In lieu of that mess with trying to find the UIBarButtonItem's view in the toolbar's subview list, you can also try this, once the item is added to the toolbar:
[barButtonItem valueForKey:#"view"];
This uses the Key-Value Coding framework to access the UIBarButtonItem's private _view variable, where it keeps the view it created.
Granted, I don't know where this falls in terms of Apple's private API thing (this is public method used to access a private variable of a public class - not like accessing private frameworks to make fancy Apple-only effects or anything), but it does work, and rather painlessly.
This is an old question, but it still comes up in google searches, and all of the other answers are overly complicated.
I have a buttonbar, with buttonbar items, that call an action:forEvent: method when pressed.
In that method, add these lines:
bool longpress=NO;
UITouch *touch=[[[event allTouches] allObjects] objectAtIndex:0];
if(touch.tapCount==0) longpress=YES;
If it was a single tap, tapCount is one. If it was a double tap, tapCount is two. If it's a long press, tapCount is zero.
Option 1 is indeed possible. Unfortunately it's a painful thing to find the UIView that the UIBarButtonItem creates. Here's how I found it:
[[[myToolbar subviews] objectAtIndex:[[myToolbar items] indexOfObject:myBarButton]] addGestureRecognizer:myGesture];
This is more difficult than it ought to be, but this is clearly designed to stop people from fooling around with the buttons look and feel.
Note that Fixed/Flexible spaces are not counted as views!
In order to handle spaces you must have some way of detecting them, and sadly the SDK simply has no easy way to do this. There are solutions and here are a few of them:
1) Set the UIBarButtonItem's tag value to it's index from left to right on the toolbar. This requires too much manual work to keep it in sync IMO.
2) Set any spaces' enabled property to NO. Then use this code snippet to set the tag values for you:
NSUInteger index = 0;
for (UIBarButtonItem *anItem in [myToolbar items]) {
if (anItem.enabled) {
// For enabled items set a tag.
anItem.tag = index;
index ++;
}
}
// Tag is now equal to subview index.
[[[myToolbar subviews] objectAtIndex:myButton.tag] addGestureRecognizer:myGesture];
Of course this has a potential pitfall if you disable a button for some other reason.
3) Manually code the toolbar and handle the indexes yourself. As you'll be building the UIBarButtonItem's yourself, so you'll know in advance what index they'll be in the subviews. You could extend this idea to collecting up the UIView's in advance for later use, if necessary.
Instead of groping around for a subview you can create the button on your own and add a button bar item with a custom view. Then you hook up the GR to your custom button.
While this question is now over a year old, this is still a pretty annoying problem. I've submitted a bug report to Apple (rdar://9982911) and I suggest that anybody else who feels the same duplicate it.
You also can simply do this...
let longPress = UILongPressGestureRecognizer(target: self, action: "longPress:")
navigationController?.toolbar.addGestureRecognizer(longPress)
func longPress(sender: UILongPressGestureRecognizer) {
let location = sender.locationInView(navigationController?.toolbar)
println(location)
}
Until iOS 11, let barbuttonView = barButton.value(forKey: "view") as? UIView will give us the reference to the view for barButton in which we can easily add gestures, but in iOS 11 the things are quite different, the above line of code will end up with nil so adding tap gesture to the view for key "view" is meaningless.
No worries we can still add tap gestures to the UIBarItems, since it have a property customView. What we can do is create a button with height & width 24 pt(according to Apple Human Interface Guidelines) and then assign the custom view as the newly created button. The below code will help you perform one action for single tap and another for tapping bar button 5 times.
NOTE For this purpose you must already have a reference to the barbuttonitem.
func setupTapGestureForSettingsButton() {
let multiTapGesture = UITapGestureRecognizer()
multiTapGesture.numberOfTapsRequired = 5
multiTapGesture.numberOfTouchesRequired = 1
multiTapGesture.addTarget(self, action: #selector(HomeTVC.askForPassword))
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
button.addTarget(self, action: #selector(changeSettings(_:)), for: .touchUpInside)
let image = UIImage(named: "test_image")withRenderingMode(.alwaysTemplate)
button.setImage(image, for: .normal)
button.tintColor = ColorConstant.Palette.Blue
settingButton.customView = button
settingButton.customView?.addGestureRecognizer(multiTapGesture)
}
I tried something similar to what Ben suggested. I created a custom view with a UIButton and used that as the customView for the UIBarButtonItem. There were a couple of things I didn't like about this approach:
The button needed to be styled to not stick out like a sore thumb on the UIToolBar
With a UILongPressGestureRecognizer I didn't seem to get the click event for "Touch up Inside" (This could/is most likely be programing error on my part.)
Instead I settled for something hackish at best but it works for me. I'm used XCode 4.2 and I'm using ARC in the code below. I created a new UIViewController subclass called CustomBarButtonItemView. In the CustomBarButtonItemView.xib file I created a UIToolBar and added a single UIBarButtonItem to the toolbar. I then shrunk the toolbar to almost the width of the button. I then connected the File's Owner view property to the UIToolBar.
Then in my ViewController's viewDidLoad: message I created two UIGestureRecognizers. The first was a UILongPressGestureRecognizer for the click-and-hold and second was UITapGestureRecognizer. I can't seem to properly get the action for the UIBarButtonItem in the view so I fake it with the UITapGestureRecognizer. The UIBarButtonItem does show itself as being clicked and the UITapGestureRecognizer takes care of the action just as if the action and target for the UIBarButtonItem was set.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(longPressGestured)];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(buttonPressed:)];
CustomBarButtomItemView* customBarButtonViewController = [[CustomBarButtomItemView alloc] initWithNibName:#"CustomBarButtonItemView" bundle:nil];
self.barButtonItem.customView = customBarButtonViewController.view;
longPress.minimumPressDuration = 1.0;
[self.barButtonItem.customView addGestureRecognizer:longPress];
[self.barButtonItem.customView addGestureRecognizer:singleTap];
}
-(IBAction)buttonPressed:(id)sender{
NSLog(#"Button Pressed");
};
-(void)longPressGestured{
NSLog(#"Long Press Gestured");
}
Now when a single click occurs in the ViewController's barButtonItem (Connected via the xib file) the tap gesture calls the buttonPressed: message. If the button is held down longPressGestured is fired.
For changing the appearance of the UIBarButton I'd suggest making a property for CustomBarButtonItemView to allow access to the Custom BarButton and store it in the ViewController class. When the longPressGestured message is sent you can change the system icon of the button.
One gotcha I've found is the customview property takes the view as is. If you alter the custom UIBarButtonitem from the CustomBarButtonItemView.xib to change the label to #"really long string" for example the button will resize itself but only the left most part of the button shown is in the view being watched by the UIGestuerRecognizer instances.
I tried #voi1d's solution, which worked great until I changed the title of the button that I had added a long press gesture to. Changing the title appears to create a new UIView for the button that replaces the original, thus causing the added gesture to stop working as soon as a change is made to the button (which happens frequently in my app).
My solution was to subclass UIToolbar and override the addSubview: method. I also created a property that holds the pointer to the target of my gesture. Here's the exact code:
- (void)addSubview:(UIView *)view {
// This method is overridden in order to add a long-press gesture recognizer
// to a UIBarButtonItem. Apple makes this way too difficult, but I am clever!
[super addSubview:view];
// NOTE - this depends the button of interest being 150 pixels across (I know...)
if (view.frame.size.width == 150) {
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:targetOfGestureRecognizers
action:#selector(showChapterMenu:)];
[view addGestureRecognizer:longPress];
}
}
In my particular situation, the button I'm interested in is 150 pixels across (and it's the only button that is), so that's the test I use. It's probably not the safest test, but it works for me. Obviously you'd have to come up with your own test and supply your own gesture and selector.
The benefit of doing it this way is that any time my UIBarButtonItem changes (and thus creates a new view), my custom gesture gets attached, so it always works!
I know this is old but I spent a night banging my head against the wall trying to find an acceptable solution. I didn't want to use the customView property because would get rid of all of the built in functionality like button tint, disabled tint, and the long press would be subjected to such a small hit box while UIBarButtonItems spread their hit box out quite a ways. I came up with this solution that I think works really well and is only a slight pain to implement.
In my case, the first 2 buttons on my bar would go to the same place if long pressed, so I just needed to detect that a press happened before a certain X point. I added the long press gesture recognizer to the UIToolbar (also works if you add it to a UINavigationBar) and then added an extra UIBarButtonItem that's 1 pixel wide right after the 2nd button. When the view loads, I add a UIView that's a single pixel wide to that UIBarButtonItem as it's customView. Now, I can test the point where the long press happened and then see if it's X is less than the X of the customview's frame. Here's a little Swift 3 Code
#IBOutlet var thinSpacer: UIBarButtonItem!
func viewDidLoad() {
...
let thinView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 22))
self.thinSpacer.customView = thinView
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPressed(gestureRecognizer:)))
self.navigationController?.toolbar.addGestureRecognizer(longPress)
...
}
func longPressed(gestureRecognizer: UIGestureRecognizer) {
guard gestureRecognizer.state == .began, let spacer = self.thinSpacer.customView else { return }
let point = gestureRecognizer.location(ofTouch: 0, in: gestureRecognizer.view)
if point.x < spacer.frame.origin.x {
print("Long Press Success!")
} else {
print("Long Pressed Somewhere Else")
}
}
Definitely not ideal, but easy enough for my use case. If you need a specify a long press on specific buttons in specific locations, it gets a little more annoying but you should be able to surround the buttons you need to detect the long press on with thin spacers and then just check that your point's X is between both of those spacers.
#voi1d's 2nd option answer is the most useful for those not wanting to rewrite all the functionality of UIBarButtonItem's. I wrapped this in a category so that you can just do:
[myToolbar addGestureRecognizer:(UIGestureRecognizer *)recognizer toBarButton:(UIBarButtonItem *)barButton];
with a little error handling in case you are interested. NOTE: each time you add or remove items from the toolbar using setItems, you will have to re-add any gesture recognizers -- I guess UIToolbar recreates the holding UIViews every time you adjust the items array.
UIToolbar+Gesture.h
#import <UIKit/UIKit.h>
#interface UIToolbar (Gesture)
- (void)addGestureRecognizer:(UIGestureRecognizer *)recognizer toBarButton:(UIBarButtonItem *)barButton;
#end
UIToolbar+Gesture.m
#import "UIToolbar+Gesture.h"
#implementation UIToolbar (Gesture)
- (void)addGestureRecognizer:(UIGestureRecognizer *)recognizer toBarButton:(UIBarButtonItem *)barButton {
NSUInteger index = 0;
NSInteger savedTag = barButton.tag;
barButton.tag = NSNotFound;
for (UIBarButtonItem *anItem in [self items]) {
if (anItem.enabled) {
anItem.tag = index;
index ++;
}
}
if (NSNotFound != barButton.tag) {
[[[self subviews] objectAtIndex:barButton.tag] addGestureRecognizer:recognizer];
}
barButton.tag = savedTag;
}
#end
I know it is not the best solution, but I am going to post a rather easy solution that worked for me.
I have created a simple extension for UIBarButtonItem:
fileprivate extension UIBarButtonItem {
var view: UIView? {
return value(forKey: "view") as? UIView
}
func addGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) {
view?.addGestureRecognizer(gestureRecognizer)
}
}
After this, you can simply add your gesture recognizers to the items in your ViewController's viewDidLoad method:
#IBOutlet weak var myBarButtonItem: UIBarButtonItem!
func setupLongPressObservation() {
let recognizer = UILongPressGestureRecognizer(
target: self, action: #selector(self.didLongPressMyBarButtonItem(recognizer:)))
myBarButtonItem.addGestureRecognizer(recognizer)
}
#utopians answer in Swift 4.2
#objc func myAction(_ sender: UIBarButtonItem, forEvent event:UIEvent) {
let longPressed:Bool = (event.allTouches?.first?.tapCount).map {$0 == 0} ?? false
... handle long press ...
}
Ready for use UIBarButtonItem subclass:
#objc protocol BarButtonItemDelegate {
func longPress(in barButtonItem: BarButtonItem)
}
class BarButtonItem: UIBarButtonItem {
#IBOutlet weak var delegate: BarButtonItemDelegate?
private let button = UIButton(type: .system)
override init() {
super.init()
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
let recognizer = UILongPressGestureRecognizer(
target: self,
action: #selector(longPress)
)
button.addGestureRecognizer(recognizer)
button.setImage(image, for: .normal)
button.tintColor = tintColor
customView = button
}
override var action: Selector? {
set {
if let action = newValue {
button.addTarget(target, action: action, for: .touchUpInside)
}
}
get { return nil }
}
#objc private func longPress(sender: UILongPressGestureRecognizer) {
if sender.state == .began {
delegate?.longPress(in: self)
}
}
}
This is the most Swift-friendly and least hacky way I came up with. Works in iOS 12.
Swift 5
var longPressTimer: Timer?
let button = UIButton()
button.addTarget(self, action: #selector(touchDown), for: .touchDown)
button.addTarget(self, action: #selector(touchUp), for: .touchUpInside)
button.addTarget(self, action: #selector(touchCancel), for: .touchCancel)
let undoBarButton = UIBarButtonItem(customView: button)
#objc func touchDown() {
longPressTimer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(longPressed), userInfo: nil, repeats: false)
}
#objc func touchUp() {
if longPressTimer?.isValid == false { return } // Long press already activated
longPressTimer?.invalidate()
longPressTimer = nil
// Do tap action
}
#objc func touchCancel() {
longPressTimer?.invalidate()
longPressTimer = nil
}
#objc func longPressed() {
// Do long press action
}