UITextField text jumps - ios

I have ViewController with 2 UITextField elements: Login and Password. I set delegate for these fields, which includes code below:
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField === self.loginField {
self.loginField.resignFirstResponder()
self.passwordField.becomeFirstResponder()
return false
}
return true
}
This logic should switch user from login text field to password when he presses Next button on keyboard. But I stuck with glitch: after
self.passwordField.becomeFirstResponder()
text in login field jumps to the top left corner and back. And what's more strange: this glitch reproduces only first time, then you need recreate ViewController to observe this behavior
Here is video of the glitch http://tinypic.com/player.php?v=6nsemw%3E&s=8#.VgVb3cuqpHx
I ended up with this:
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField === self.loginField {
self.loginField.resignFirstResponder()
// Shitty workaround. Hi, Apple!
self.loginField.setNeedsLayout()
self.loginField.layoutIfNeeded()
self.passwordField.becomeFirstResponder()
return false
}
return true
}

Based on some of the other ideas posted here, this is a solution that is easy to implement, works (for me) in all cases, and doesn't appear to have any side effects:
- (void)textFieldDidEndEditing:(UITextField *)textField
{
// Workaround for the jumping text bug.
[textField resignFirstResponder];
[textField layoutIfNeeded];
}
This solution works both if you're going to the next field programmatically from -textFieldShouldReturn: or if the user just touches another responder.

In a UITextField subclass you can do the following:
-(BOOL)resignFirstResponder
{
BOOL resigned = [super resignFirstResponder];
[self layoutIfNeeded];
return resigned;
}
The trick here is to make sure you call layoutIfNeeded after resignFirstResponder has been called.
Doing it this way is quite handy because you don't need to call resignFirstResponder in the delegate callbacks yourself as this caused me problems inside a UIScrollView, the above however doesn't :)

func textFieldDidEndEditing(_ textField: UITextField) {
textField.layoutIfNeeded()
}

Use this code to avoid the jumping of text in UITextField.
- (BOOL) textFieldShouldReturn:(UITextField *)textField{
if(textField == self.txtUserName){
[self.txtEmail becomeFirstResponder];
}
else if (textField == self.txtEmail){
[self.txtPassword becomeFirstResponder];
}
else if (textField == self.txtPassword){
[self.txtConfirmPassword becomeFirstResponder];
}
else if (textField == self.txtConfirmPassword){
[self.txtFirstName becomeFirstResponder];
}
else{
[textField resignFirstResponder];
}
return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
[textField resignFirstResponder];
[textField layoutIfNeeded];
}

I'm also facing the same problem. The below code is worked for me.
func textFieldDidEndEditing(_ textField: UITextField) {
textField.layoutIfNeeded()
}

More "generic" option is to use notifications right inside your UITextField subclass:
- (void)setupJumpingTextWorkaround {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(forceLayout)
name:UITextFieldTextDidEndEditingNotification object:self];
}
- (void)forceLayout {
[self setNeedsLayout];
[self layoutIfNeeded];
}
Do not forget to unsubscribe

Based on what I understand from this:
This issue can be caused when you have layout changes or animations handled in the callbacks for keyboard will show and hide notifications (usually in cases when you want the textfield to be pushed up so the keyboard won't hide it).
Solution:
I was facing this problem as I was doing layoutIfNeeded every time keyboard will show got called assuming its safe, obviously its not, so when I put a check to do that only when there is a need for changing the frames, the jump stopped.

I don't give my text fields delegates. Instead I create an IBAction and attach it to the "Did End On Exit" event. The glitch happens with this method too, but only in iOS 9. It looks to be an OS bug.
My action looks like this:
#IBAction func textFieldAction(sender: UITextField) {
if sender === usernameField {
passwordField.becomeFirstResponder()
}
}
With the above, the glitch happens, but when I do the below the glitch goes away:
#IBAction func textFieldAction(sender: UITextField) {
if sender === usernameField {
sender.resignFirstResponder()
passwordField.becomeFirstResponder()
}
}
I don't seem to need to call setNeedsLayout().

Related

UITextField "Next" Adding Extra Newline to UITextView [duplicate]

I have a scroll view which contains a UITextField and a UITextView. The UITextField return key is "Next" and when this is pressed I call [myTextView becomeFirstResponder]; A random new line is inserted into my textview so I start on the second line. How do I avoid this?
Also important to note that this does not happen when I tap directly on the UITextView rather than tapping the next key.
Thanks in advance!
One solution to solve this is when you implement the textFieldShouldReturn: delegate method, be sure to return NO, and not YES. By returning NO, the newline isn't passed on to the text field.
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
// move to next field or whatever you need
[myTextView becomeFirstResponder];
return NO;
}
Okay, this behaviour is due to a bug in iOS when becoming firstresponder within same run loop by using next button. To over come this you should do this manually.
First resign first responder from a textFied, and then make textView as a first responder. like this. Implement this delegate method.
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
[textView performSelector:#selector(becomeFirstResponder) withObject:nil afterDelay:0.0];
return YES;
}
Similar idea to performSelector, but using asynchronous dispatch queue (Swift 4 version):
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
DispatchQueue.main.async {
self.myTextView.becomeFirstResponder()
}
return true
}

When Will textFieldDidEndEditing:textField be called?

I have 2 UITextField in a ViewController. One brings up a UIDatePicker another brings up a KeyBoard(number pad). I then assign user inputs to two class variables, a NSDate variable and a NSNumber variable, in the following method.
-(void)textFieldDidEndEditing:(UITextField *)textField{
if (textField == self.datePickerTextField){
//update xxtime
self.xxTime = self.datePicker.date;
NSLog(#"...%#",self.xxTime);
}
if (textField == self.numberTextField) {
int val = [textField.text intValue];
self.xxNumber = [NSNumber numberWithInt:val];
NSLog(#"...%#",self.xxNumber);
}
}
If I tap the datePickerTextField first then the numberTextField, this method won't get called after I finish typing in the numberTextField.
So my question is how do I make this method to get called? Should I specify "resignFirstResponder" somewhere?
TIA
It will invoke didEndEditing once another control gains focus
According to the API,
This method is called after the text field resigns its first responder
status.
So if you want didEndEditing to be invoked, you need to call
[textField resignFirstResponder];
Yo are right you need to specify resignFirstResponder
- (BOOL)textFieldShouldReturn:(UITextField *)textField {//Text Field Delegate
if (textField == textField1) {
[textField1 becomeFirstResponder];
}else{
[textField resignFirstResponder];
}
return TRUE; }
this can used with textFieldDidEndEditing also
Please check what iOS you are using. Remember that if you are using iOS 10, there is a method that is replacing the old textFieldDidEndEditing called func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason)

How to disable keyboard appearing when hitting on a text field , iOS?

I have a text field , and i need when the user presses it to show a custom picker.
The picker is shown fine , but the problem is that the keyboard appears on the bottom and i dont want that.
This is an iPad project which i am trying to convert from my iphone one. On the iPhone , this works well and the keyboard is always hidden.
What could i be missing/forgetting to do here ?
EDIT
For future reference what actually happened here , was that in fact both times (iphone & ipad) the keyboard was not hidden. I just thought that it was hidden in the iphone because my picker , which was popping from the bottom was hiding the keyboard as it was on top of it. But on ipad this wasnt the case.
Anyway i fixed it , using the delegate method suggested below.
Caution , i accepted this answer cause it was the one answering specifically what i wanted. The rest of the answers are correct and my considered better for other implementations.
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
// Here You can do additional code or task instead of writing with keyboard
return NO;
}
this delegate method will get called first when you hit to textfield and if you write NO as a boolean value means you dont want to begin editing so it will not present Keyboard.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if(textfield == yourtextField)
{
[textfield resignFirstResponder];
// Show you custom picker here....
return NO;
}
}
and you need to implement the uitextfielddelegate in the controller.
and give assign the delegate to yourtextField.
Use textfield delegate.
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
return NO;
}
It looks like all of these answers take one approach, to simply deny the keyboard before it comes up. This prevents first responder status, which has many advantages.
One simple approach that allows you to maintain first responder status is to create an empty view and assign that to the inputView property on your input field. If you are using iOS 9 (or later?) you will also have to get rid of the inputAssistantItem objects as well.
UITextField *field = [[UITextField alloc] init];
field.inputView = self.emptyKeyboard.view;
UITextInputAssistantItem *aItem = [field inputAssistantItem];
aItem.leadingBarButtonGroups = #[];
aItem.trailingBarButtonGroups = #[];
Then if you want to control the field from an alternate view controller, you can do so by adding targets:
[field addTarget:self.numberPad action:#selector(editingBegan:) forControlEvents:UIControlEventEditingDidBegin];
[field addTarget:self.numberPad action:#selector(editingEnded:) forControlEvents:UIControlEventEditingDidEnd];
[field addTarget:self.numberPad action:#selector(fieldChanged:) forControlEvents:UIControlEventEditingChanged];
It is also possible to do this a lot more cleanly by subclassing UITextField.
Use the textField Delegate,
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
textField=nil;
return NO;
}
swift 3.0 version
First set the delegate for the text field
self.textfield.delegate = self
Then in an extension
extension ViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return false
}
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
// Here you can do for Specific text Field by
if (textField==(the text field you don't want to show keyboard)) {
NSLog(#"don't show keyboard");
return NO;
}
else {
return YES;
}
}
Swift 3/4
Add:- UITextFieldDelegate in your class.
Add:- self.textField.delegate = self In ViewDidLoad
last one just add this func -
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return false
}

How do I dismiss the iOS keyboard?

I have a UITextfield that i'd like to dismiss the keyboard for. I can't seem to make the keyboard go away no matter what code i use.
If you have multiple text fields and don't know which one is first responder (or you simply don't have access to the text fields from wherever you are writing this code) you can call endEditing: on the parent view containing the text fields.
In a view controller's method, it would look like this:
[self.view endEditing:YES];
The parameter forces the text field to resign first responder status. If you were using a delegate to perform validation and wanted to stop everything until the text field's contents were valid, you could also code it like this:
BOOL didEndEditing = [self.view endEditing:NO];
if (didEndEditing) {
// on to the next thing...
} else {
// text field must have said to first responder status: "never wanna give you up, never wanna let you down"
}
The endEditing: method is much better than telling individual text fields to resignFirstResponder, but for some reason I never even found out about it until recently.
[myTextField resignFirstResponder]
Here, second paragraph in the Showing and Hiding the Keyboard section.
I've discovered a case where endEditing and resignFirstResponder fail. This has worked for me in those cases.
ObjC
[[UIApplication sharedApplication] sendAction:#selector(resignFirstResponder) to:nil from:nil forEvent:nil];
[self setEditing:NO];
Swift
UIApplication.shared.sendAction(#selector(resignFirstResponder), to: nil, from: nil, for: nil)
There are cases where no text field is the first responder but the keyboard is on screen.
In these cases, the above methods fail to dismiss the keyboard.
One example of how to get there:
push the ABPersonViewController on screen programmatically; open any contact;
touch the "note" field (which becomes first responder and fires up the keyboard);
swipe left on any other field to make the "delete" button appear;
by this point you have no first responder among the text fields (just check programmatically) but the keyboard is still there. Calling [view endEditing:YES] does nothing.
In this case you also need to ask the view controller to exit the editing mode:
[viewController setEditing:NO animated:YES];
I suggest you add and action on your header file:
-(IBAction)removeKeyboard;
And in the implementation, write something like this:
-(IBAction)removeKeyboard
{
[self.textfield resignFirstResponder];
}
In the NIB file, connect from the UITextFiled to the File's Owner on the option DidEndOnExit. That way, when you press return, the keyboard will disappear.
Hope it helps!
In your view controller YourViewController.h file, make sure you implement UITextFieldDelegate protocol :
#interface YourViewController : <UITextFieldDelegate>
#end
Then, in YourViewController.m file, implement the following instance method:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.yourTextField1 resignFirstResponder];
[self.yourTextField2 resignFirstResponder];
...
[self.yourTextFieldn resignFirstResponder];
}
To resign any text field in the app
UIApplication.shared.keyWindow?.endEditing(true)
This approach is clean and guarantied to work because the keyWindow is, by definition, the root view of all possible views displaying a keyboard (source):
The key window receives keyboard and other non-touch related events. Only one window at a time may be the key window.
This will resign one particular text field
// Swift
TextField.resignFirstResponder()
// Objective C
[TextField resignFirstResponder];
To resign any text field use below code
// Swift
self.view!.endEditing(true)
// Objective C
[self.view endEditing:YES];
as a last resort đź’©
let dummyTextView = UITextView(frame: .zero)
view.addSubview(dummyTextView)
dummyTextView.becomeFirstResponder()
dummyTextView.resignFirstResponder()
dummyTextView.removeFromSuperview()
If you don't know which textField is the first responder you can find it. I use this function:
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;
}
Then in your code call:
UIView *resigned = resignFirstResponder([UIScreen mainScreen]);
You just replace yourTextFieldName with, you guessed it! your textfield. This will close the keyboard.
[yourTextFieldName resignFirstResponder];
-(void)methodName
{
[textFieldName resignFirstResponder];
}
call this method (methodName) with didEndOnExit
For Swift 3
You can hide the keyboard like this:
textField.resignFirstResponder()
If you want to hide the keyboard when the user press the "intro" button, you have to implement the following UITextFieldDelegate method:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
// your code
[textField reloadInputViews];
}
3 Simple & Swift steps
Add UITextFieldDelegate to your class as below:
class RegisterVC: UIViewController, UITextFieldDelegate {
//class implementation
}
in class implementation, add the delegate function textFieldShouldEndEditing::
internal func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return true
}
and as a last step, set your UITextField(s) delegate(s) to self, in somewhere appropriate. For example, inside the viewDidLoad function:
override func viewDidLoad(){
super.viewDidLoad()
myTextField1.delegate = self
myTextField2.delegate = self
..
..
}
Now, whenever user hits the return key, keyboard will dismiss.
I prepared an example snippet too, you can check it from here.
Set up the "Did End On Exit" event in Xcode (right click on your text field).
Realize this method:
-(IBAction) closeKeyboard:(id) sender {
[_txtField resignFirstResponder];
}

How do you dismiss the keyboard when editing a UITextField

I know that I need to tell my UITextField to resign first responder when I want to dismis the keyboard, but I'm not sure how to know when the user has pressed the "Done" key on the keyboard. Is there a notification I can watch for?
I set the delegate of the UITextField to my ViewController class.
In that class I implemented this method as following:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
If you connect the DidEndOnExit event of the text field to an action (IBAction) in InterfaceBuilder, it will be messaged when the user dismisses the keyboard (with the return key) and the sender will be a reference to the UITextField that fired the event.
For example:
-(IBAction)userDoneEnteringText:(id)sender
{
UITextField theField = (UITextField*)sender;
// do whatever you want with this text field
}
Then, in InterfaceBuilder, link the DidEndOnExit event of the text field to this action on your controller (or whatever you're using to link events from the UI). Whenever the user enters text and dismisses the text field, the controller will be sent this message.
You can also create a method in your controller
-(IBAction)editingEnded:(id)sender{
[sender resignFirstResponder];
}
and then in Connection Inspector in IB connect Event "Did End On Exit" to it.
kubi, thanks. Your code worked. Just to be explicit (for newbies like) as you say you have to set the UITextField's delegate to be equal to the ViewController in which the text field resides. You can do this wherever you please. I chose the viewDidLoad method.
- (void)viewDidLoad
{
// sets the textField delegates to equal this viewController ... this allows for the keyboard to disappear after pressing done
daTextField.delegate = self;
}
Here is a trick for getting automatic keyboard dismissal behavior with no code at all. In the nib, edit the First Responder proxy object in the Identity inspector, adding a new first responder action; let's call it dummy:. Now hook the Did End on Exit event of the text field to the dummy: action of the First Responder proxy object. That's it! Since the text field's Did End on Exit event now has an action–target pair, the text field automatically dismisses its keyboard when the user taps Return; and since there is no penalty for not finding a handler for a message sent up the responder chain, the app doesn't crash even though there is no implementation of dummy: anywhere.
In Swift you can write an IBAction in the Controller and set the Did End On Exit event of the text field to that action
#IBAction func returnPressed(sender: UITextField) {
self.view.endEditing(true)
}
Just add
[textField endEditing:YES];
where you want to disable keyboard and display the picker view.
Swift 4.2 and It will work 100%
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.textField.delegate = self
}
// hide key board when the user touches outside keyboard
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
// user presses return key
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
You can also use
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.yourTextField resignFirstResponder];
}
Best one if You have many Uitextfields :
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
Here's what I had to do to get it to work, and I think is necessary for anyone with a Number Pad for a keyboard (or any other ones without a done button:
I changed the UIView in the ViewController to a UIControl.
I created a function called
-(IBAction)backgroundIsTapped:(id)sender
This was also defined in the .h file.
After this, I linked to to the 'touch down' bit for the ViewController in Interface Builder.
In the 'background is tapped' function, I put this:
[answerField resignFirstResponder];
Just remember to change 'answerField' to the name of the UITextField you want to remove the keyboard from (obviously make sure your UITextField is defined like below:)
IBOutlet UITextField * <nameoftextfieldhere>;
I know this topic probably died a long time ago... but I'm hoping this will help someone, somewhere!
You will notice that the method "textFieldShouldReturn" provides the text-field object that has hit the DONE key. If you set the TAG you can switch on that text field. Or you can track and compare the object's pointer with some member value stored by its creator.
My approach is like this for a self-study:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
NSLog(#"%s", __FUNCTION__);
bool fDidResign = [textField resignFirstResponder];
NSLog(#"%s: did %resign the keyboard", __FUNCTION__, fDidResign ? #"" : #"not ");
return fDidResign;
}
Meanwhile, I put the "validation" test that denies the resignation follows. It is only for illustration, so if the user types NO! into the field, it will not dismiss. The behavior was as I wanted, but the sequence of output was not as I expected.
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
NSLog(#"%s", __FUNCTION__);
if( [[textField text] isEqualToString:#"NO!"] ) {
NSLog(#"%#", textField.text);
return NO;
} else {
return YES;
}
}
Following is my NSLog output for this denial followed by the acceptance. You will notice that I am returning the result of the resign, but I expected it to return FALSE to me to report back to the caller?! Other than that, it has the necessary behavior.
13.313 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldReturn:]
13.320 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldEndEditing:]
13.327 StudyKbd[109:207] NO!
13.333 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldReturn:]: did resign the keyboard
59.891 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldReturn:]
59.897 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldEndEditing:]
59.917 StudyKbd[109:207] -[StudyKbdViewController doneEditText]: NO
59.928 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldReturn:]: did resign the keyboard
Here is a quite clean way to end edition with the Return Key or a touch in the background.
In Interface builder, embed your fields in a view of class UIFormView
What does this class :
Automatically attach itself as fields delegate ( Either awaked from nib, or added manually )
Keep a reference on the current edited field
Dismiss the keyboard on return or touch in the background
Here is the code :
Interface
#import <UIKit/UIKit.h>
#interface UIFormView : UIView<UITextFieldDelegate>
-(BOOL)textFieldValueIsValid:(UITextField*)textField;
-(void)endEdit;
#end
Implementation
#import "UIFormView.h"
#implementation UIFormView
{
UITextField* currentEditingTextField;
}
// Automatically register fields
-(void)addSubview:(UIView *)view
{
[super addSubview:view];
if ([view isKindOfClass:[UITextField class]]) {
if ( ![(UITextField*)view delegate] ) [(UITextField*)view setDelegate:self];
}
}
// UITextField Protocol
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
currentEditingTextField = textField;
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
currentEditingTextField = NULL;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self endEdit];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if ([self textFieldValueIsValid:textField]) {
[self endEdit];
return YES;
} else {
return NO;
}
}
// Own functions
-(void)endEdit
{
if (currentEditingTextField) {
[currentEditingTextField endEditing:YES];
currentEditingTextField = NULL;
}
}
// Override this in your subclass to handle eventual values that may prevent validation.
-(BOOL)textFieldValueIsValid:(UITextField*)textField
{
return YES;
}
#end
By subclassing the form and overriding the
textFieldValueIsValid: method, you
can avoid end of edition if the value is not correct for the given
field.
If a field has a delegate set in Interface Builder, then the form does not change it. I don't see many reasons to set a different delegate to a particular field, but why not…
There is many ways to improve this form view class - Attach a delegate, do some layout, handle when the keyboards covers a field ( using the currentEditingTextField frame ), automatically start edition for the next field, ...
I personally keep it in my framework, and always subclass it to add features, it is quite often useful "as-is".
I hope it will helps. Cheers all
if you want all editing of in a UIViewController you can use.
[[self view]endEditing:YES];
and if you want dismiss a perticular UITextField keyboard hide then use.
1.add delegate in your viewcontroller.h
<UITextFieldDelegate>
make delegation unable to your textfield .
self.yourTextField.delegate = self;
add this method in to your viewcontroller.
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{
[textField resignFirstResponder];
return YES;}
Anyone looking for Swift 3
1) Make sure your UITextField's Delegate is wired to your ViewController in the Storyboard
2) Implement UITextFieldDelegate in your ViewController.Swift file (e.g class ViewController: UIViewController, UITextFieldDelegate { )
3) Use the delegate method below
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false }
Programmatically set the delegate of the UITextField in swift 3
Implement UITextFieldDelegate in your ViewController.Swift file (e.g class ViewController: UIViewController, UITextFieldDelegate { )
lazy var firstNameTF: UITextField = {
let firstname = UITextField()
firstname.placeholder = "FirstName"
firstname.frame = CGRect(x:38, y: 100, width: 244, height: 30)
firstname.textAlignment = .center
firstname.borderStyle = UITextBorderStyle.roundedRect
firstname.keyboardType = UIKeyboardType.default
firstname.delegate = self
return firstname
}()
lazy var lastNameTF: UITextField = {
let lastname = UITextField()
lastname.placeholder = "LastName"
lastname.frame = CGRect(x:38, y: 150, width: 244, height: 30)
lastname.textAlignment = .center
lastname.borderStyle = UITextBorderStyle.roundedRect
lastname.keyboardType = UIKeyboardType.default
lastname.delegate = self
return lastname
}()
lazy var emailIdTF: UITextField = {
let emailid = UITextField()
emailid.placeholder = "EmailId"
emailid.frame = CGRect(x:38, y: 200, width: 244, height: 30)
emailid.textAlignment = .center
emailid.borderStyle = UITextBorderStyle.roundedRect
emailid.keyboardType = UIKeyboardType.default
emailid.delegate = self
return emailid
}()
// Mark:- handling delegate textField..
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == firstNameTF {
lastNameTF.becomeFirstResponder()
}
else if textField == lastNameTF {
emailIdTF.becomeFirstResponder()
}
else {
view.emailIdTF(true)
}
return true
}
Create a function hidekeyboard and link it to the textfield in the .xib file and select DidEndOnExit
-(IBAction)Hidekeyboard
{
textfield_name.resignFirstResponder;
}
If you have created the view using Interface Builder, Use the following
Just create a method,
-(IBAction)dismissKeyboard:(id)sender
{
[sender resignFirstResponder];
}
Just right click the text field in the view , and set the event as Did End on Exit, and wire it to the method "dismissKeyboard".
The best guide for beginners is
"Head First iPhone and iPad Development, 2nd Edition"
try this
- (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
{
if ([text isEqualToString:#"\n"]) {
[textView resignFirstResponder];
return NO;
}
return YES;
}
//====================================================
// textFieldShouldReturn:
//====================================================
-(BOOL) textFieldShouldReturn:(UITextField*) textField {
[textField resignFirstResponder];
if(textField.returnKeyType != UIReturnKeyDone){
[[textField.superview viewWithTag: self.nextTextField] becomeFirstResponder];
}
return YES;
}
This is how I dismiss the keyboard in Swift 4.2 and it works for me:
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action:
#selector(dismissKeyboard))
view.addGestureRecognizer(tap)
}
#objc func dismissKeyboard (_ sender: UITapGestureRecognizer) {
numberField.resignFirstResponder()
}
Swift 3, iOS 9+
#IBAction private func noteFieldDidEndOnExit(_ sender: UITextField) {}
UPD: It still works fine for me. I think guy that devoted this answer just didn't understand that he needs to bind this action to the UITextField at the storyboard.
textField.returnKeyType = UIReturnKeyDone;

Resources