Unable to hide the keyboard in iOS - ios

I am trying to hide the keyboard in an iOS app. I've spent several hours looking for it, and I've tried pretty much everything, so I'm quite desperate.
My code follows as next:
RNViewController.h
#interface RNViewController : UIViewController <UITextFieldDelegate> {
UITextField *textField;
...
}
RNController.m
- (void)viewDidLoad {
textField.delegate = self;
textField.returnKeyType = UIReturnKeyDone;
}
- (BOOL)textFieldShouldReturn:(id)sender {
NSLog(#"Entering in textFieldShouldReturn ");
[textField resignFirstResponder];
return YES;
}
- (BOOL)textViewShouldReturn:(id)sender {
NSLog(#"Entering in textViewShouldReturn ");
[textField resignFirstResponder];
return YES;
}
- (IBAction)textFieldDoneEditing:(id)sender {
NSLog(#"Entering in textFieldDoneEditing ");
[sender resignFirstResponder];
}
- (IBAction)textViewDoneEditing:(id)sender {
NSLog(#"Entering in textViewDoneEditing ");
[sender resignFirstResponder];
}
- (BOOL)disablesAutomaticKeyboardDismissal {
return NO;
}
EDIT: The textField is created dinamically like this:
- (void) showPreguntaTexto: (Pregunta *) pregunta {
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetWidth(baseView.bounds)*0.1, offset + CGRectGetWidth(baseView.bounds)*0.05, CGRectGetWidth(baseView.bounds) - CGRectGetWidth(baseView.bounds) * 0.2 , CGRectGetWidth(baseView.bounds)*0.5)];
textField.delegate = self;
[vistaAnterior addSubview:textField];
}
My views are the baseView (with elements that do not change) and vistaAnterior, that has the content (and the textField) and changes.
Trying this, it shows that entered to textFieldShouldReturn, but the keyboard does not dissapear.
Why is this happening?? Please help!!

Resign the sender of the textfield instead of your instance. UITextField *textField is not an IBOutlet (storyboard) or created in code so textField is nil (unless you created it somewhere else and didn't show the code).
- (BOOL)textViewShouldReturn:(id)sender {
NSLog(#"Entering in textViewShouldReturn ");
[sender resignFirstResponder];
return YES;
}

have you set text fields delegate in your RNViewController from stroyboard. This might be a reason for keyboard not hiding.

Related

keyboard not disappear when used resignFirstResponder in iOS

coding environment sierra 10.12,Xcode 8.1. Two textField in my roorView, if first textfield's text is nil, second textfield will can't be editing.When i used resignFirstResponder method to turn off keyboard in textFieldDidBeginEditing: method, keyboard not disappear. I add a fullscreen TapGesture in rootView. I'm very confused,anyone have ideas to help me deal with this problem?
`
#pragma mark -- UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
if (textField == self.password) {
[self.username resignFirstResponder];
NSString *name = self.username.text;
if ([name isEqualToString:#""]) {
[CFBlurHUD showFaild:#"sign in error!"];
[self performSelector:#selector(dismmiss) withObject:nil afterDelay:1.5f];
self.password.enabled = NO;
}
}
}
- (void)dismmiss{
[CFBlurHUD dismiss];
self.password.enabled = YES;
}
`
If you want to simply dismiss a keyboard from view, try the following:
self.view.endEditing = true;
use your UITextFieldDelegate methods specifically UITextFieldShouldBeginEditing and return NO and execute the code to show the popover instead. This way the keyboard is never shown to begin with
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
[self.view endEditing:YES];
return NO;
}
Because current textfiled is password: if (textField == self.password) {. But you set:
[self.username resignFirstResponder];
It 's not correct.
Try:
[self.username resignFirstResponder];
[self.password resignFirstResponder];
or :
self.view.endEditting = true;
use your UITextFieldDelegate methods specifically UITextFieldShouldBeginEditing and return NO and execute the code to show the popover instead. This way the keyboard is never shown to begin with
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
[self.view endEditing:YES];
return NO;
}
First step for dismiss keyboard Give textfeild delegate in storyboard
Or Also give by code :
self.txtName.delegate = self;
Dismiss keyboard when tap gesture method called:
- (void)dismmiss{
[self.view endEditing:YES];
[CFBlurHUD dismiss];
self.password.enabled = YES;
}
or Also Dismiss when touch anywhere in View:
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self.view endEditing:YES];
}
Or when user press return button in keyboard:
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}

Navigation using return button in apple keyboard

I have more than one text field in my view controller how can i navigate from one to another using the return button in the IOS keyboard.
Use UITextFieldDelegate delegate and the textFieldShouldReturn: method. Inside you can get the tag of the textfield passed in argument and direct to another one based on this information.
To have the delegate working you have to set delegate property of sender (textfield) to be the receiver (e.g. your view controller)
myTextField.delegate = self;
or do it in the storyboard (here is some storyboard hints). Your view controller then needs to specify this delegate as follows (in the "h" file):
#interface MyViewController:UIViewController<UITextFieldDelegate>
#end
and then in the "m" file
-(BOOL)textFieldShouldReturn:(UITextField*)textfield{
if([textfield tag] == 1)
{
//pass focus to next textfield
[self.nextTextField becomeFirstResponder];
} else {
//remove focus from current textfield
[textfield resignFirstResponder];//
}
return YES;//YES if textfield should implement its default behaviour
}
-(BOOL) textFieldShouldReturn: (UITextField *) textField
{
[textField resignFirstResponder];
if(textField == _your1stTextField)
[_your2ndTextField becomeFirstResponder];
return YES;
}
try this...
set delegates to all of your text fields and then..
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == textField1)
{
[textField2 becomeFirstResponder];
}
else if (textField == textField2)
{
[textField3 becomeFirstResponder];
}
else if textField == textField3)
{
[textField4 becomeFirstResponder];
}
.
.
.
[textField resignFirstResponder];
return YES;
}
I think this solution is more dynamic as it works for any number of textFields as long as your superview doesn't have a view with a tag == lastTextField.tag + 1
In viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
self.textField1.delegate = self;
self.textField2.delegate = self;
...
self.lastTextField.delegate = self;
self.textField1.tag = 1;
self.textField2.tag = 2;
...
self.lastTextField.tag = n;
}
Then implement the textFieldDelegate:
-(BOOL) textFieldShouldReturn:(UITextField *)textField
{
NSInteger nextTag = textField.tag + 1;
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder)
[nextResponder becomeFirstResponder];
else
[textField resignFirstResponder];
return NO;
}
You need to declare at .h
.m set
yourTextfieldRef1.delegate=self;
yourTextfieldRef2.delegate=self;
yourTextfieldRef3.delegate=self;
yourTextfieldRef4.delegate=self;
yourTextfieldRef5.delegate=self;
.
.
.
set
yourTextFieldRef1.tag=1;
yourTextFieldRef2.tag=2;
yourTextFieldRef3.tag=3;
yourTextFieldRef4.tag=4;
yourTextFieldRef5.tag=5;
.
.
.
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
NSInteger nextTag = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// Not found, so remove keyboard.
[textField resignFirstResponder];
}
return YES;
}
Hope it helps you...!

How to dismiss keyboard iOS programmatically when pressing return

I created a UITextField programmatically making the UITextField a property of the viewController. I need to dismiss the keyboard with the return and the touch on the screen. I was able to get the screen touch to dismiss, but pressing return is not working.
I've seen how to do it with storyboards and by allocating and initializing the UITextField object directly without creating it as a property. Possible to do?
.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITextFieldDelegate>
#property (strong, atomic) UITextField *username;
#end
.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor blueColor];
self.username = [[UITextField alloc] initWithFrame:CGRectMake(100, 25, 80, 20)];
self.username.placeholder = #"Enter your username";
self.username.backgroundColor = [UIColor whiteColor];
self.username.borderStyle = UITextBorderStyleRoundedRect;
if (self.username.placeholder != nil) {
self.username.clearsOnBeginEditing = NO;
}
_username.delegate = self;
[self.view addSubview:self.username];
[_username resignFirstResponder];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(#"touchesBegan:withEvent:");
[self.view endEditing:YES];
[super touchesBegan:touches withEvent:event];
}
#end
The simple way is to connect the delegate of UITextField to self (self.mytestField.delegate = self) and dismiss the keyboard in the method textFieldShouldReturn using [textField resignFirstResponder];
Another way to dismiss the keyboard is the following:
Objective-C
[self.view endEditing:YES];
Swift:
self.view.endEditing(true)
Put [self.view endEditing:YES]; where you would like to dismiss the keyboard (Button event, Touch event, etc.).
Add a delegate method of UITextField like this:
#interface MyController : UIViewController <UITextFieldDelegate>
And set your textField.delegate = self; then also add two delegate methods of UITextField
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
return YES;
}
// It is important for you to hide the keyboard
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
simply use this in swift to dismiss keyboard:
UIApplication.sharedApplication().sendAction("resignFirstResponder", to:nil, from:nil, forEvent:nil)
Swift 3
UIApplication.shared.sendAction(#selector(UIResponder.resign‌​FirstResponder), to: nil, from: nil, for: nil)
//Hide keyBoard by touching background in view
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[[self view] endEditing:YES];
}
SWIFT 4:
self.view.endEditing(true)
or
Set text field's delegate to current viewcontroller and then:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
Objective-C:
[self.view endEditing:YES];
or
Set text field's delegate to current viewcontroller and then:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
In the App Delegate, you can write
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.window endEditing:YES];
}
use this way, you can don`t write too much code.
Try to get an idea about what a first responder is in iOS view hierarchy. When your textfield becomes active(or first responder) when you touch inside it (or pass it the messasge becomeFirstResponder programmatically), it presents the keyboard. So to remove your textfield from being the first responder, you should pass the message resignFirstResponder to it there.
[textField resignFirstResponder];
And to hide the keyboard on its return button, you should implement its delegate method textFieldShouldReturn: and pass the resignFirstResponder message.
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
Here's what I use in my code. It works like a charm!
In yourviewcontroller.h add:
#property (nonatomic) UITapGestureRecognizer *tapRecognizer;
Now in the .m file, add this to your ViewDidLoad function:
- (void)viewDidLoad {
[super viewDidLoad];
//Keyboard stuff
tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleSingleTap:)];
tapRecognizer.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:tapRecognizer];
}
Also, add this function in the .m file:
- (void)handleSingleTap:(UITapGestureRecognizer *) sender
{
[self.view endEditing:YES];
}
For a group of UITextViews inside a ViewController:
Swift 3.0
for view in view.subviews {
if view is UITextField {
view.resignFirstResponder()
}
}
Objective-C
// hide keyboard before dismiss
for (UIView *view in [self.view subviews]) {
if ([view isKindOfClass:[UITextField class]]) {
// no need to cast
[view resignFirstResponder];
}
}
To dismiss a keyboard after the keyboard has popped up, there are 2 cases,
when the UITextField is inside a UIScrollView
when the UITextField is outside a UIScrollView
2.when the UITextField is outside a UIScrollView
override the method in your UIViewController subclass
you must also add delegate for all UITextView
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
}
In a scroll view, Tapping outside will not fire any event, so in that case use a Tap Gesture Recognizer,
Drag and drop a UITapGesture for the scroll view and create an IBAction for it.
to create a IBAction, press ctrl+ click the UITapGesture and drag it to the .h file of viewcontroller.
Here I have named tappedEvent as my action name
- (IBAction)tappedEvent:(id)sender {
[self.view endEditing:YES]; }
the abouve given Information was derived from the following link, please refer for more information or contact me if you dont understand the abouve data.
http://samwize.com/2014/03/27/dismiss-keyboard-when-tap-outside-a-uitextfield-slash-uitextview/
I know this have been answered by others, but i found the another article that covered also for no background event - tableview or scrollview.
http://samwize.com/2014/03/27/dismiss-keyboard-when-tap-outside-a-uitextfield-slash-uitextview/
Since the tags only say iOS i will post the answer for Swift 1.2 and iOs 8.4, add these in your view controller swift class:
// MARK: - Close keyboard when touching somewhere else
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true)
}
// MARK: - Close keyboard when return pressed
func textFieldShouldReturn(textField: UITextField!) -> Bool {
textField.resignFirstResponder()
return true
}
// MARK: -
Also do not forget to add UITextFieldDelegate in the class declaration and set your text fields delegate to self (the view).
IN Swift 3
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
OR
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == yourtextfieldName
{
self.resignFirstResponder()
self.view.endEditing(true)
}
}
First you need to add textfield delegete in .h file. if not declare
(BOOL)textFieldShouldReturn:(UITextField *)textField this method not called.so first add delegate and write keyboard hide code into that method.
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
try this one..
So here's what I did to make it dismiss after touching the background or return. I had to add the delegate = self in viewDidLoad and then also the delegate methods later in the .m files.
.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITextFieldDelegate>
#property (strong, atomic) UITextField *username;
#end
.m
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor blueColor];
self.username = [[UITextField alloc] initWithFrame:CGRectMake(100, 25, 80, 20)];
self.username.placeholder = #"Enter your username";
self.username.backgroundColor = [UIColor whiteColor];
self.username.borderStyle = UITextBorderStyleRoundedRect;
if (self.username.placeholder != nil) {
self.username.clearsOnBeginEditing = NO;
}
self.username.delegate = self;
[self.username resignFirstResponder];
[self.view addSubview:self.username];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
#end
Simply use this in Objective-C to dismiss keyboard:
[[UIApplication sharedApplication].keyWindow endEditing:YES];
Add Delegate : UITextFieldDelegate
#interface ViewController : UIViewController <UITextFieldDelegate>
and then add this delegate method
// This should work perfectly
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view.subviews enumerateObjectsUsingBlock:^(UIView* obj, NSUInteger idx, BOOL *stop) {
if ([obj isKindOfClass:[UITextField class]]) {
[obj resignFirstResponder];
}
}];
}
when you using more then one textfield in screen
With this method you doesn't need to mention textfield every time like
[textField1 resignFirstResponder];
[textField2 resignFirstResponder];
Swift 2 :
this is what is did to do every thing !
close keyboard with Done button or Touch outSide ,Next for go to next input.
First Change TextFiled Return Key To Next in StoryBoard.
override func viewDidLoad() {
txtBillIdentifier.delegate = self
txtBillIdentifier.tag = 1
txtPayIdentifier.delegate = self
txtPayIdentifier.tag = 2
let tap = UITapGestureRecognizer(target: self, action: "onTouchGesture")
self.view.addGestureRecognizer(tap)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if(textField.returnKeyType == UIReturnKeyType.Default) {
if let next = textField.superview?.viewWithTag(textField.tag+1) as? UITextField {
next.becomeFirstResponder()
return false
}
}
textField.resignFirstResponder()
return false
}
func onTouchGesture(){
self.view.endEditing(true)
}
If you don't know current view controller or textview you can use the Responder Chain:
UIApplication.shared.sendAction(#selector(UIView.endEditing(_:)), to:nil, from:nil, for:nil)
for swift 3-4 i fixed like
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return false
}
just copy paste anywhere on the class. This solution just work if you want all UItextfield work as same, or if you have just one!

How to change event of return key? [duplicate]

This question already has answers here:
How to navigate through textfields (Next / Done Buttons)
(35 answers)
Closed 9 years ago.
i have 4 text fields , i want to parform following actions by clicking on return key -
1- when i enter entry in one field and press return key , curser should be jumped on next
TextField .
Thanks .
Implement UITextField delegate and set tag value to all your textField in series. like 1,2,3..as so on. then, make sure scrollView and textField tag values should not conflict.
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
int nextTextFieldTag = textField.tag+1;
UITextField *textFieldd = (UITextField*)[self.view viewWithTag:nextTextFieldTag];
if (textFieldd!=nil) {
if ([textField isKindOfClass:[UITextField class]]) {
[textFieldd becomeFirstResponder];
return NO;
}
}
return YES;
}
Try this
Take the 4 textfields as textfield1,textfield2,textfile3,textfield4 .
In the textfield delegate method
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if([textField isEqual:textfield1])
{
[textfield2 becomeFirstResponder];
return NO;
}
else if([textField isEqual:textfield2])
{
[textfield3 becomeFirstResponder];
return NO;
}
// Do for other textfields
return YES;
}
You just need to know what the next TextField should be and have UITextFieldDelegateProtocol especially the - (BOOL)textFieldShouldReturn:(UITextField *)textField implemented.
In - (BOOL)textFieldShouldReturn:(UITextField *)textField simply figure out the next TextField and do [nextTextField becomeFirstResponder];
So the - (BOOL)textFieldShouldReturn:(UITextField *)textField Method could look like this:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if ([textField isEqual:firstTextField]) {
[secondTextField becomeFirstResponder];
}
//When last textfield dismiss the keyboard
else if ([textField lastTextField]) {
[textField resignFirstResponder];
}
return NO;
}

Go back to previous UITextfield , IOS

My app has a registration view, I compare strings in password textfield and confirm password textfield , if they dont match I want user go back to password textfield
This question done it with using tags
UITextField jump to previous
Is there a way to accomplish this without using tags?
//call next textfield on each next button
- (BOOL) textFieldShouldReturn:(UITextField *) textField {
BOOL didResign = [textField resignFirstResponder];
if (!didResign) return NO;
if ([textField isKindOfClass:[SOTextField class]])
dispatch_async(dispatch_get_current_queue(),
^ { [[(SOTextField *)textField nextField] becomeFirstResponder]; });
return YES;
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
if (textField==self.confirmPassword) {
if ([self.password.text isEqualToString:self.confirmPassword.text]) {
NSLog(#"password fields are equal");
}
else{
NSLog(#"password fields are not equal prompt user to enter correct values");
//[self.password becomeFirstResponder]; doesnt work
}
}
}
Without using tags, you could create an NSArray of textfield outlets the describes the desired ordering.
Declare and init like this ...
#property(nonatomic,strong) NSArray *textFields;
- (NSArray *)textFields {
if (!_textFields) {
// just made these outlets up, put your real outlets in here...
_textFields = [NSArray arrayWithObjects:self.username, self.password, nil];
}
return _textFields;
}
You'll need to fetch the text field that currently has focus, if there is one...
- (UITextField *)firstResponderTextField {
for (UITextField *textField in self.textFields) {
if ([textField isFirstResponder]) return textField;
}
return nil;
}
Then advance focus like this...
- (void)nextFocus {
UITextField *focusField = [self firstResponderTextField];
// what should we do if none of the fields have focus? nothing
if (!focusField) return;
NSInteger index = [self.textFields indexOfObject:textField];
// advance the index in a ring
index = (index == self.textFields.count-1)? 0 : index+1;
UITextField *newFocusField = [self.textFields objectAtIndex:index];
[newFocusField becomeFirstResponder];
}
And move focus backward like this...
- (void)previousFocus {
UITextField *focusField = [self firstResponderTextField];
// what should we do if none of the fields have focus? nothing
if (!focusField) return;
NSInteger index = [self.textFields indexOfObject:textField];
// backup the index in a ring
index = (index == 0)? self.textFields.count-1 : index-1;
UITextField *newFocusField = [self.textFields objectAtIndex:index];
[newFocusField becomeFirstResponder];
}

Resources