UIAlertView displaying keyboard, not able to dismiss it - ios

I have an application that uses UIAlertView in its login Window normally:
self.customAlert = [[IFCustomAlertView alloc] initWithTitle:#"Save Password"
message:#"¿Do you want the app to remember your password?"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:#"Cancel", nil];
The problem is... Since I updated my devices to iOS8 whenever this alertView comes up it shows the keyboard and I can't dismiss it. On iOS7 this doesn't happen.
I am resigning the responders of user and password when the send button is tapped:
-(IBAction)btnSendTapped:(id)sender{
[self.tfpass resignFirstResponder];
[self.tfuser resignFirstResponder];
}
I have tried:
[self.view endEditing:YES];
and in some alertViews it does work but in others it doesn't. My AlertViews never have text fields so I think there's no reason for this keyboard to appear.
Also the intro button on the keyboard doesn't hide it, so sometimes the OK and Cancel buttons are obstructed by the keyboard and I can't do nothing on the screen.
I think this may have something to to with the UIAlertView deprecation, but I don't know.
I also have these methods implemented:
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return true;
}
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{
return YES;
}
Any help would be appreciated.

I borrow solution from this blog
For me the keyboard always show up when the alertView.show() has been called.
My solution is using the didPresentALertView method for make sure this will called after the alert view popup. Then we can loop through all UIWindows and it's subviews. I detect it by description name (You can use more accurate method if you want) and just simply remove it from superview.
func didPresentAlertView(alertView: UIAlertView) {
var tempWindow: UIWindow;
var keyboard: UIView;
for var c = 0; c < UIApplication.sharedApplication().windows.count; c++ {
tempWindow = UIApplication.sharedApplication().windows[c] as! UIWindow
for var i = 0; i < tempWindow.subviews.count; i++ {
keyboard = tempWindow.subviews[i] as! UIView
println(keyboard.description)
if keyboard.description.hasPrefix("<UIInputSetContainerView") {
keyboard.removeFromSuperview()
}
}
}
}
Hope this thelp.

Related

Hide Keyboard on clear click in UISearchBar and not backspace to empty text

I cant seem to find this answer for the manually clearing the UISearchBar with a backspace, only with a cancel button click. The code below hides the keyboard when the clear button is clicked, but so does the backspace to an empty UISearchBar. Id like to leave the keyboard open in that scenario since someone might be typing something else.
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
[self filterData: text];
if(text.length == 0)
{
[searchBar performSelector:#selector(resignFirstResponder) withObject:nil afterDelay:.1];
}
}
Your code includes if(text.length == 0) and that means that when the size of the input becomes zero, keyboard is dismissed. However the actual piece should be as follows:
- (BOOL) searchBarCancelButtonClicked:(UISearchBar *)searchBar{
[searchBar resignFirstResponder];
return YES;
}
My best try on such an issue is to do as suggested here BUT IT DOES NOT WORK WHEN YOU CLICK CLEAR BUTTON :( but I thought it might help you though:
https://stackoverflow.com/a/16957073/1465756
Add a tap gesture on your whole view:
- (void)viewDidLoad
{
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:#selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
}
and dismissKeyboard when the view is tapped:
- (void) dismissKeyboard
{
[self.searchBar resignFirstResponder];
}
I understand you want to dismiss the keyboard when the user hits Cancel, and you also want to dismiss when the user hits the clear (x) button.
You do not need to implement searchBar:textDidChange:.
To detect cancellation, implement searchBarCancelButtonClicked:. Here you can trigger resignFirstResponder.
To detect clear, adopt UITextFieldDelegate and implement textFieldShouldClear:. This will be called after the user taps clear, but before the clear occurs. Return YES to allow the clear to occur. You may dismiss the keyboard before returning.

iOS UIAlertview clear text and disable OK

I'm a bit new to iOS development, and right now am working on some simple UI-related stuff. I have a UIAlertView that I'm using at one point to allow the user to enter some text, with simple Cancel and OK buttons. The OK button should be disabled if the text field is blank.
I added to my UIAlertViewDelegate an alertViewShouldEnableFirstOtherButton function, so the OK button would disable when there's no text, and I also set the UIAlertView's UITextField to have clearOnBeginEditing true, so the previous text would be gone every time I displayed the alert. Each of these things works perfectly on their own. Unfortunately, it seems like the AlertView is checking whether or not to enable the OK button before the text field is cleared, so when they're put together it comes up enabled. Below should be about the minimal code needed to reproduce.
-(void)viewDidLoad
{
textEntryBox = [[UIAlertView alloc] initWithTitle:#"Name" message:nil delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
[textEntryBox setAlertViewStyle:UIAlertViewStylePlainTextInput];
[textEntryBox textFieldAtIndex:0].clearsOnBeginEditing = YES;
}
-(IBAction)functionTriggeredByOtherLogic
{
[textEntryBox show];
}
-(BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
if(alertView == textEntryBox)
{
if([[alertView textFieldAtIndex:0].text length] > 0)
{
return YES;
}
else
{
return NO;
}
}
return YES;
}
So, ultimately, my question is this: am I doing something completely against the natural iOS way of doing things here? Is there a better way to do this? Should I just ignore the clearsOnBeginEditing property of the UITextField, and manually clear the Text property before showing the UIAlertView?
Try to set the textfield delegate to self
[[textEntryBox textFieldAtIndex:0] setDelegate:self]
and implement this method :
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
[textField setText:#""];
}
I'm also having a UIAlertView with a textField to fill-in in my app, and it works for me
Using an alert view for this is probably a bit much. It might be easier if you use the master-detail paradigm and just push a new view controller where you can enter your values.

iOS SDK: Disable text dictation for UITextField [duplicate]

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
}

iOS iPad app not hiding keyboard

In my app I have a view that is a form that has quite a few inputs.
When the UITextField calls textFieldDidBeginEditing, it checks the tag and will bring up a UIPopoverController or the keyboard depending on the what the input is meant to be.
If the keyboard is up, I need it disappear when the user presses a textfield that brings up the popover. However I cannot make it disappear, I have tried every way to get rid of the keyboard but it just stays there. I have tried:
calling resignFirstResponder in textFieldDidEndEditing
calling [self.view endEditing:YES] in textFieldDidEndEditing
calling resignFirstResponder AND [self.view endEditing:YES] in textFieldDidBeginEditing checking for the previous tag is equal to a keyboard input text field.
Any ideas would be great.
I have ripped it out and and put it in a example project if anyone wants to see the exact behaviour.
http://dl.dropbox.com/u/61692457/KB_Test.zip
Declare a Global UITextField in .h file
UITextField *txtfld;
Replace Your method textFieldDidBeginEditing with textFieldShouldBeginEditing and now write this code
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if (textField.tag == 1 || textField.tag==3)
{
if(numPickerPopover == nil)
{
numPicker = [[[NumPicker alloc] initWithStyle:UITableViewStylePlain] autorelease];
numPicker.delegate = self;
numPickerPopover = [[UIPopoverController alloc] initWithContentViewController:numPicker];
[numPickerPopover setPopoverContentSize:CGSizeMake(60.0, 260.0f)];
}
[numPickerPopover presentPopoverFromRect:textField.frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
[txtfld resignFirstResponder];
return NO;
}
if (textField.tag == 2)
{
txtfld = textField;
return YES;
}
return YES;
}
To dismiss the keyboard when the user touches the textField that brought it up, add this method:
- (IBAction)dismissKeyboard:(id)sender {
[textField resignFirstResponder];
}
In Interface Builder, connect this method to the textField event you want, like touch up inside (or whatever is more appropriate).

ipad keyboard dismissal callback [duplicate]

I realize that this is the inverse of most posts, but I would like for the keyboard to remain up even if the 'keyboard down' button is pressed.
Specifically, I have a view with two UITextFields. With the following delegate method
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
return NO;
}
I am able to keep the keyboard up even if the user presses the Done button on the keyboard or taps anywhere else on the screen EXCEPT for that pesky keyboard down button on the bottom right of the keyboard.
I am using this view like a modal view (though the view is associated with a ViewController that gets pushed in a UINavigationController), so it really works best from a user perspective to keep the keyboard up all of the time. If anyone knows how to achieve this, please let me know! Thanks!
UPDATE Still no solution! When Done is pressed, it triggers textFieldShouldReturn, but when the Dismiss button is pressed, it triggers textFieldDidEndEditing. I cannot block the textField from ending editing or it never goes away. Somehow, I really want to have a method that detects the Dismiss button and ignores it. If you know a way, please enlighten me!
There IS a way to do this. Because UIKeyboard subclasses UIWindow, the only thing big enough to get in UIKeyboard's way is another UIWindow.
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(coverKey) name:UIKeyboardDidShowNotification object:nil];
[super viewDidLoad];
}
- (void)coverKey {
CGRect r = [[UIScreen mainScreen] bounds];
UIWindow *myWindow = [[UIWindow alloc] initWithFrame:CGRectMake(r.size.width - 50 , r.size.height - 50, 50, 50)];
[myWindow setBackgroundColor:[UIColor clearColor]];
[super.view addSubview:myWindow];
[myWindow makeKeyAndVisible];
}
This works on iPhone apps. Haven't tried it with iPad. You may need to adjust the size of myWindow. Also, I didn't do any mem management on myWindow. So, consider doing that, too.
I think I've found a good solution.
Add a BOOL as instance variable, let's call it shouldBeginCalledBeforeHand
Then implement the following methods:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
shouldBeginCalledBeforeHand = YES;
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
return shouldBeginCalledBeforeHand;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
shouldBeginCalledBeforeHand = NO;
}
As well as
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
return NO;
}
to prevent the keyboard from disappearing with the return button. The trick is, a focus switch from one textfield to another will trigger a textFieldShouldBeginEditing beforehand. If the dismiss keyboard button is pressed this doesn't happen. The flag is reset after a textfield has gotten focus.
Old not perfect solution
I can only think of a not perfect solution. Listen for the notification UIKeyboardDidHideNotification and make of the textfields first responder again. This will move the keyboard out of sight and back again. You could keep record of which textfield was the last firstResponder by listening for UIKeyboardWillHideNotification and put focus on it in the didHide.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardDidHide:)
name:UIKeyboardDidHideNotification
object:nil];
...
- (void)keyboardDidHide:(id)sender
{
[myTextField becomeFirstResponder];
}
For iOS 9/10 and Swift 3, use this to create a rect which overlaps the "Hide keyboard" - Button
override func viewDidLoad() {
NotificationCenter.default.addObserver(self, selector: #selector(coverKey), name: .UIKeyboardDidShow, object: nil)
}
func coverKey() {
if let keyboardWindow = UIApplication.shared.windows.last {
let r = UIScreen.main.bounds
let myWindow = UIWindow.init(frame: CGRect(x: r.size.width - 50 , y: r.size.height - 50, width: 50, height: 50))
myWindow.backgroundColor = UIColor.clear
myWindow.isHidden = false
keyboardWindow.addSubview(myWindow)
keyboardWindow.bringSubview(toFront: myWindow)
}
}
Notice that this adds a sub view to the keyboard window instead of the main window
Try adding a custom on top of the keyboard dismiss button so that the user won't be able to tab the dismiss button. I have used this method in one of my application.
- (void)addButtonToKeyboard {
// create custom button
UIButton *blockButton = [UIButton buttonWithType:UIButtonTypeCustom];
blockButton.frame = //set the frame here, I don't remember the exact frame
[blockButton setImage:[UIImage imageNamed:#"block_button.png"] forState:UIControlStateNormal];
// locate keyboard view
UIWindow *appWindows = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
UIView *keyboard;
for (int i=0; i<[appWindows.subviews count]; i++) {
keyboard = [appWindows.subviews objectAtIndex:i];
// keyboard found, add the button
if ([[keyboard description] hasPrefix:#"<UIPeripheralHost"] == YES && [self.textField isFirstResponder]) {
[keyboard addSubview:doneButton];
}
}
}
Try this...
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
return NO;
}
You can use notification as mentioned by Nick Weaver.

Resources