How to hide the keypad after use - ios

Hei, is there an easy way to add - that after the input into a text field and pressing a button the keypad is disappearing from the screen?
I found here this answer: in button action routine write [yourTextField resignFirstResponder]. it will hide your keyboard.
But I dont get it where to place that code [yourTextField resignFirstResponder]
Thanks for help!

If you simply want to dismiss the keyboard when the user presses the return key, simply add this to viewDidLoad in order to receive delegate callbacks from your textfield:
- (void)viewDidLoad
{
[super viewDidLoad];
self.myTextfield.delegate = self;
}
And then implement this method that hides the keyboard when the user presses the return key:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
And in Swift:
override func viewDidLoad() {
super.viewDidLoad()
myTextfield.delegate = self
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
textField.resignFirstResponder()
return false
}
If you're not pressing the return key, but your own UIButton, you'll have to do something like this:
#IBAction func findBudget(sender: AnyObject) {
myTextfield.resignFirstResponder()
// .. rest of your code.
}

Related

Dismiss keyboard on tapping textfield

I have a textfield which can be edited. Below this textfield, I have another textfield on the tap of which I go to another screen.
When I tap the 1st textfield, the keyboard comes up. But when I tap on the 2nd textfield the keyboard still remains (maybe because it is also a textfield). But I want the keyboard to dismiss the moment I tap the second textfield.
I'm using IQKeyboardManager.
This is what I have..But it's not working...
#IBAction func secondTextfield_Clicked(_ sender: Any) {
(sender as! UITextField).resignFirstResponder()
self.performSegue(withIdentifier: "mySegue", sender: nil)
}
First you need to set the delegate to the second textfield and implement the textFieldShouldBeginEditing delegate method.
secondTextField.delegate = self
In the following delegate method you can check the textfield and return true/false based on your textfield.
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
view.endEditing(true) //with will end editing for the view
if textField == secondTextField {
self.performSegue(withIdentifier: "mySegue", sender: nil)
return false
}
return true
}
By returning false for the secondTextField the keyboard will not be opened for the second text field.
First of all why are you using textfield to go to anther page?
why don't you just use button instead
Second thing, if you want you can do this:
override func viewDidLoad() {
super.viewDidLoad()
...
secondTF.delegate = self
...
}
And call this function anywhere in your code:
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
view.endEditing(true)
if textField == secondTF {
// Navigate to the second VC with using storyBoard or navigationController
return false
}
return true
}

Hide and Unhide button programmatically

I am trying to hide a button while a text field is empty then show it when the user starts typing.
I tried making an outlet for the button and in viewDidLoad used a while loop to implement the outlet for the button and the text field. It did not work, i been searching around but most of the code are objective-C so i have a hard time translating it to swift.
Is it even possible to hide a button while a text field is empty?
Swift preferred
Use UITextFieldDelegate to hide and show button.
class ViewController: UIViewController,UITextFieldDelegate //set delegate to class
#IBOutlet var txtValue: UITextField //create a textfile variable
override func viewDidLoad() {
super.viewDidLoad()
txtValue.delegate = self
YourButton.hidden=false;
//set delegate to textfile
}
func textFieldDidBeginEditing(textField: UITextField!)
{ //delegate method
YourButton.hidden=true;
}
func textFieldShouldEndEditing(textField: UITextField!) -> Bool { //delegate method
return false
}
func textFieldShouldReturn(textField: UITextField!) -> Bool { //delegate method
textField.resignFirstResponder()
return true
}
May be it will help you.
Try This Code:
func textField(textField: UITextField, shouldChangeCharactersInRange range:NSRange, replacementString string: String) -> Bool
{
text = text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
var strMsg: String = textView.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if strMsg.length() > 0 || text.length() > 0
{
self.YourButton.alpha = 1.0
self.YourButton.enabled = true
}
else
{
self.YourButton.alpha = 0.5
self.YourButton.enabled = false
}
return true
}
Firstly you have to hide button by using this code.
btn1.hidden = YES;
After Assign UITextFieldDelegate to file owner, also implement the same delegate in .h file
after than when you start writing writing some text on textfield you this code.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
[self updateTextLabelsWithText: newString];
return YES;
}
-(void)updateTextLabelsWithText:(NSString *)string
{
[myLabel setText:string];
}
When textfield text run use
btn1.hidden = NO;
Hope this helps.

How to dismiss keyboard when user tap other area outside textfield?

today I tried to run my code on my iPod (iOS 6.1.3) and I found something interesting here...
first, when I tap on textfield the keyboard shows up but it won't hide when I tap somewhere else outside textfield.
so I decided to Googling and found this solution :
_fieldEmail.delegate = self;
_fieldEmail.returnKeyType = UIReturnKeyDone;
_fieldPassword.delegate = self;
_fieldPassword.returnKeyType = UIReturnKeyDone;
_fieldRegisterName.delegate = self;
_fieldRegisterName.returnKeyType = UIReturnKeyDone;
_fieldRegisterEmail.delegate = self;
_fieldRegisterEmail.returnKeyType = UIReturnKeyDone;
_fieldRegisterPassword.delegate = self;
_fieldRegisterPassword.returnKeyType = UIReturnKeyDone;
it works... it gives a 'DONE' button on the bottom of keyboard and now the keyboard can be hidden by pressing it.
but I have 2 problems here :
the keyboard only hide when 'DONE' button is tapped. not by tapping other area outside text field. I don't know if this normal on iOS world, but usually I see lot of apps don't act like this.
is there any way to loop this process so I don't have manually add that delegate one by one of all textfield that I have? how to do that?
that's all I need to know
The below code will work on all the components in the UIView for all the UITextField
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for (UIView * txt in self.view.subviews){
if ([txt isKindOfClass:[UITextField class]] && [txt isFirstResponder]) {
[txt resignFirstResponder];
}
}
}
OR
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
}
Simply add an UITapGestureRecogniser to your view that will lead to calling resignFirstResponder
In viewDidLoad :
UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:#selector(hideKeyBoard)];
[self.view addGestureRecognizer:tapGesture];
And then :
-(void)hideKeyBoard {
[yourTextField resignFirstResponder];
}
2.You could subclass UITextField but unless you have 1000 textFields it is ok to do like you currently do.
This is regards to Swift programming for Xcode 6.0.1
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let tapRecognizer = UITapGestureRecognizer(target: self, action: "handleSingleTap:")
tapRecognizer.numberOfTapsRequired = 1
self.view.addGestureRecognizer(tapRecognizer)
}
func handleSingleTap(recognizer: UITapGestureRecognizer) {
self.view.endEditing(true)
}
Use Either
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleTap];
and code of method
-(void)handleSingleTap:(UITapGestureRecognizer *)sender{
[self.TextFiledName resignFirstResponder];
}
OR _ And The best Other option is
Just add
[self.view endEditing:YES];
And key board will hide when you tapped anywhere from view:)
Dismissing the keyboard
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self.view endEditing:YES];
[super touchesBegan:touches withEvent:event];
}
Simple,
Use IQKeyboardManager and put this line of code in AppDelegate.m
[[IQKeyboardManager sharedManager] setShouldResignOnTouchOutside:YES];
What I usually do is call
[field resignFirstResponder];
from an invisible button over the view. I'm sure theres a nicer way to do it. It's been a while since I've done this in an app.
Here's how I do it:
In the myView's .h file:
#property (strong) UITextField * savedTextField;
In the myView's .m file:
#implementation myView
#synthesize savedTextField;
In the myView's init routine:
[self setSavedTextField: nil];
In the myView's textField delegate area I save the id of whichever textField is currently activating:
- (BOOL) textFieldShouldBeginEditing: (UITextField *) textField
{
[self setSavedTextField: textField];
.
.
.
return( YES );
}
And in the myView's routine that routes all the traffic for the other controls when they are accessed, I have code that looks to see if a textField was active and, if one was, it calls on it to resign its FirstResponder status and then drops a nil into the savedTextField property:
- (void) handleCtrlEvents: (UIControl *) aCtrl
{
if ( [self savedTextField] != nil )
{
[[self savedTextField] resignFirstResponder];
[self setSavedTextField: nil];
}
.
.
.
}
This works cleanly for me.
I ran into the exact same problem. Usually what you want is, that wherever you click inside your App (which is displayed in your main / current UIView) but not on the keyboard to close it. After searching the web for a smart solution and testing several, I think it is the best to extend/subclass/implement the UIGestureRecognizerDelegate
Since many controls such as UITableView etc. can respond to gestures (select, scrolling etc.) and if you simply add a UITapGestureRecognizer to the whole (main-)ViewController's view to close the keyboard, the user experience is not the best, since the user needs to tap twice if he didn't intend to close the keyboard but e.g. select a row from a UITableView inside the App's current "main" View.
Since I am quite new to the whole iOS and swift thing and swift code examples are rare, here's my full keyboard control snipped:
class ViewController: UIViewController, UIGestureRecognizerDelegate {
override func viewDidLoad(){
self.initializeCloseKeyboardTap()
}
func initializeCloseKeyboardTap() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onKeyboardOpen:", name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onKeyboardClose:", name: UIKeyboardDidHideNotification, object: nil)
let tapRecognizer = UITapGestureRecognizer(target: self, action: "handleOnTapAnywhereButKeyboard:")
tapRecognizer.delegate = self //delegate event notifications to this class
self.view.addGestureRecognizer(tapRecognizer)
}
func onKeyboardClose(notification: NSNotification) {
println("keyboardClosed")
}
func onKeyboardOpen(notification: NSNotification) {
println("keyboardOpen")
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
self.view.endEditing(true)
return false
}
you can nest it inside the ViewController and call initiallizeCloseKeyboardTa() in viewDidLoad implementation... It also implements a norfication observer to receive events as soon as the keyboard (finished to be) opened or closed via NSNotificationCenter UIKeyboardDidShowNotification and UIKeyboardDidHideNotification
Hope that save's other people some time :-)
|*| Dismissing the UITextField’s Keyboard : override the method touchesBegan:withEvent: for the ViewController
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
|OR|
override func viewDidLoad()
{
super.viewDidLoad()
// For tapping outside text box
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(DismisKeyPadFnc)))
}
// For tapping outside text box
func DismisKeyPadFnc()
{
view.endEditing(true)
}
|*| Dismissing the UITextField’s Keyboard on induvidual textbox :
class NamVcc: UIViewController, UITextFieldDelegate
{
#IBOutlet var NamTxtBoxVid: UITextField!
override func viewDidLoad()
{
super.viewDidLoad()
// For hitting return key
NamTxtBoxVid.delegate = self
// For tapping outside text box
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(DismisKeyPadFnc)))
}
/* For hitting return key */
func textFieldShouldReturn(NamTxtBoxPsgVid: UITextField) -> Bool
{
NamTxtBoxPsgVid.resignFirstResponder()
return true
}
/* For tapping outside text box */
func DismisKeyPadFnc()
{
view.endEditing(true)
}
}
|*| Implementing Next button Click :
1) You will be needing to set the tags in the incremental sequence of the textfields in xib/Storyboard or in code.
2) Set the delegate for each of the textfields.
3) Then paste the following code in your view controller to have the desired effect:
func textFieldShouldReturn(TxtBoxPsgVar: UITextField) -> Bool
{
let NxtTxtBoxTagVal : Int = TxtBoxPsgVar.tag + 1
let NxtTxtBoxVal: UIResponder? = TxtBoxPsgVar.superview?.superview?.viewWithTag(NxtTxtBoxTagVal)
if let TxtBoxVal = NxtTxtBoxVal
{
// Found next responder, so set it.
TxtBoxVal.becomeFirstResponder()
}
else
{
// Not found, so remove keyboard.
TxtBoxPsgVar.resignFirstResponder()
}
return true
}
I prefer IQKeyboardManager. You can simply handle keyboard in any state. To active IQKeyboard just add one line in AppDelegate and to dismiss keyboard on outside touch add code as below,
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
IQKeyboardManager.shared.enable = true
IQKeyboardManager.shared.shouldResignOnTouchOutside = true
return true
}
I think
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
is convenient but not the best solution.
and the TapGestureRecongnizer is better but hard to use,you have to set delegates and add and remove the Recongnizer.
So I wrote a simple subclass which can be easily used:
class TapHideTextField: UITextField {
override func awakeFromNib() {
super.awakeFromNib()
tapGr = UITapGestureRecognizer(target: self, action:"tap")
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didBeginEditing", name:UITextFieldTextDidBeginEditingNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didEndEditing", name:UITextFieldTextDidEndEditingNotification, object: nil)
}
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
var tapGr:UITapGestureRecognizer!
func tap(){
self.endEditing(true)
}
func didBeginEditing(){
self.superview!.addGestureRecognizer(tapGr)
}
func didEndEditing(){
self.superview!.removeGestureRecognizer(tapGr)
}
}
you should concern about the superview and the cancelTouchesInView property.
or in GitHub:https://github.com/lilidan/TapHideText/blob/master/TapHideTextField.swift
If you're using scroll view (or table view) controller, add these lines there:
override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
view.endEditing(true)
}
-(void) textFieldDidBeginEditing: (UITextField *) textField{
[self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(DismissKeyboard:)]];
}
-(void) DismissKeyboard:(UITapGestureRecognizer *) sender{
[self.view endEditing:YES];
[self.view removeGestureRecognizer:sender];
}

Action of the "Go" button of the ios keyboard

How do I bind an action to the Go button of the keyboard in iOS ?
Objective-C
Assuming you're using a UITextField, you could use the <UITextFieldDelegate> method textFieldShouldReturn.
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder]; // Dismiss the keyboard.
// Execute any additional code
return YES;
}
Don't forget to assign the class you put this code in as the text field's delegate.
self.someTextField.delegate = self;
Or if you'd prefer to use UIControlEvents, you can do the following
[someTextField addTarget:self action:#selector(textFieldDidReturn:) forControlEvents:UIControlEventEditingDidEndOnExit];
- (void)textFieldDidReturn:(UITextField *)textField
{
// Execute additional code
}
See #Wojtek Rutkowski's answer to see how to do this in Interface Builder.
Swift
UITextFieldDelegate
class SomeViewController: UIViewController, UITextFieldDelegate {
let someTextField = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
someTextField.delegate = self
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder() // Dismiss the keyboard
// Execute additional code
return true
}
}
UIControlEvents
class SomeViewController: UIViewController {
let someTextField = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
// Action argument can be Selector("textFieldDidReturn:") or "textFieldDidReturn:"
someTextField.addTarget(self, action: "textFieldDidReturn:", forControlEvents: .EditingDidEndOnExit)
}
func textFieldDidReturn(textField: UITextField!) {
textField.resignFirstResponder()
// Execute additional code
}
}
You can connect UITextFiled event Did End On Exit in Connections Inspector. It is triggered after tapping Go / Return / whatever you choose as Return Key in Attributes Inspector.

how to add an action on UITextField return key?

I have a button and text textfield in my view. when i click on the textfield a keyboard appears and i can write on the textfield and i also able to dismiss the keyboard by clicking on the button by adding:
[self.inputText resignFirstResponder];
Now I want to enable return key of keyboard. when i will press on the keyboard keyboard will disappear and something will happen. How can I do this?
Ensure "self" subscribes to UITextFieldDelegate and initialise inputText with:
self.inputText.delegate = self;
Add the following method to "self":
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField == self.inputText) {
[textField resignFirstResponder];
return NO;
}
return YES;
}
Or in Swift:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == inputText {
textField.resignFirstResponder()
return false
}
return true
}
With extension style in swift 3.0
First, set up delegate for your text field.
override func viewDidLoad() {
super.viewDidLoad()
self.inputText.delegate = self
}
Then conform to UITextFieldDelegate in your view controller's extension
extension YourViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == inputText {
textField.resignFirstResponder()
return false
}
return true
}
}
While the other answers work correctly, I prefer doing the following:
In viewDidLoad(), add
self.textField.addTarget(self, action: #selector(onReturn), for: UIControl.Event.editingDidEndOnExit)
and define the function
#IBAction func onReturn() {
self.textField.resignFirstResponder()
// do whatever you want...
}
Just add a target on textField setup function on viewDidLoad, then add its related function as selector.
override func viewDidLoad() {
super.viewDidLoad()
textField.addTarget(self, action: #selector(textFieldShouldReturn(sender:)), for: .primaryActionTriggered)
}
#objc func textFieldShouldReturn(sender: UITextField) {
textField.resignFirstResponder()
}
Use Target-Action UIKit mechanism for "primaryActionTriggered" UIEvent sent from UITextField when a keyboard done button is tapped.
textField.addTarget(self, action: Selector("actionMethodName"), for: .primaryActionTriggered)

Resources