Recognise a text by tapping on it in a textField Swift - ios

I am a newbie and want to make a custom class for a UITextView where I will be able to get the text by tapping on it within the UITextView. How to create Custom UITextView class?

Try this, I have created custom textview class and protocol that you need to confirm in your class and implement that method to get text of textview every time when you click textview.
class CustomTextView: UITextView {
weak var delegateCustomTV: CustomTextViewDelegate?
override func awakeFromNib() {
super.awakeFromNib()
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.textViewTapped))
self.addGestureRecognizer(tapGestureRecognizer)
}
#objc func textViewTapped() {
delegateCustomTV?.preparedText(text: self.text ?? "")
}
}
protocol CustomTextViewDelegate: class {
func preparedText(text: String)
}
use like i have used below,
class yourViewController: UIViewController, CustomTextViewDelegate {
#IBOutlet weak var textView: CustomTextView!
override func viewDidLoad() {
super.viewDidLoad()
textView.delegateCustomTV = self
}
func preparedText(text: String) {
// You will get your text here when you click on textview
print(text)
}
}

Try this
override func viewDidLoad() {
super.viewDidLoad()
self.textView.delegate = self
}
extension YourViewController: UITextViewDelegate
{
//MARK:- TextView Editing begins Function
func textViewDidBeginEditing(_ textView: UITextView)
{
//TextView Editing Begin Function
}
// MARK:- TextView text replaced Function
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
{
//Character changed in textView
return true
}
// MARK:- TextView End Editing function
func textViewDidEndEditing(_ textView: UITextView)
{
//End editing of textView
}
}

if you want to get text every time you tap textview you have to add tap gesture
override func viewDidLoad() {
super.viewDidLoad()
self.textView.delegate = self
let tap = UITapGestureRecognizer(target: self, action: #selector(self.textViewTapped(_:)))
self.textView.addGestureRecognizer(tap)
}
#objc func textViewTapped(_ sender: UITapGestureRecognizer){
print(textView.text)
}

Related

Swift - custom default component with delegate

I want to write a custom text view by inheriting default UITextView. My implementation uses some of the methods from the delegate of the original component:
class CustomTextView: UITextView {
fileprivate func applyStyles() {
self.layer.cornerRadius = 5
self.layer.borderColor = .black
self.layer.borderWidth = 5
self.clipsToBounds = true
}
override func awakeFromNib() {
super.awakeFromNib()
applyStyles()
delegate = self
}
}
extension CustomTextView: UITextViewDelegate {
func textViewDidBeginEditing(_ textView: UITextView) {
print("aaaa")
}
func textViewDidEndEditing(_ textView: UITextView) {
print("bbbb")
}
}
Now I want to use this text view everywhere instead of the standard one, but in the current implementation, I lose the ability to set another delegate to the component without losing the delegate functions of my own.
I mean if I will create a component in other class like this:
let customView = CustomTextView()
customView.delegate = self
textViewDidBeginEditing and textViewDidEndEditing functions in CustomTextView will not be called. How can I get around this limitation? Thanks.
The trick is to override the delegate property, so that you can capture any value that is assigned and then call that delegate after your code is done. For this to work, your subclass will need to implement all of the UITextViewDelegate functions in order to pass the invocation on to the "real" delegate:
class CustomTextView: UITextView {
private weak var externalDelegate: UITextViewDelegate?
override var delegate: UITextViewDelegate? {
set {
self.externalDelegate = newValue
}
get {
return self.externalDelegate
}
}
fileprivate func applyStyles() {
self.layer.cornerRadius = 5
self.layer.borderColor = UIColor.black.cgColor
self.layer.borderWidth = 5
self.clipsToBounds = true
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
super.delegate = self
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
super.delegate = self
}
}
extension CustomTextView: UITextViewDelegate {
func textViewDidBeginEditing(_ textView: UITextView) {
print("aaaa")
self.externalDelegate?.textViewDidBeginEditing?(textView)
}
func textViewDidEndEditing(_ textView: UITextView) {
print("bbbb")
self.externalDelegate?.textViewDidEndEditing?(textView)
}
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
return self.externalDelegate?.textViewShouldEndEditing?(textView) ?? true
}
func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
return self.externalDelegate?.textViewShouldEndEditing?(textView) ?? true
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
return (self.externalDelegate?.textView?(textView, shouldChangeTextIn: range, replacementText: text)) ?? true
}
func textViewDidChange(_ textView: UITextView) {
self.externalDelegate?.textViewDidChange?(textView)
}
func textViewDidChangeSelection(_ textView: UITextView) {
self.externalDelegate?.textViewDidChangeSelection?(textView)
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
return self.externalDelegate?.textView?(textView, shouldInteractWith: URL, in: characterRange, interaction: interaction) ?? true
}
func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
return self.externalDelegate?.textView?(textView, shouldInteractWith: textAttachment, in: characterRange, interaction: interaction) ?? true
}
}
Despite the reason may be unclear behind the fact that you want the callback to be triggered both inside the custom textview class and the parentVc , but you can do
class CustomTextView: UITextView , UITextViewDelegate {
weak var parentVC:VCName?
func textViewDidBeginEditing(_ textView: UITextView) {
print("aaaa")
parentVC?.textViewDidBeginEditing(self)
}
let customView = CustomTextView()
customView.parentVC = self
or do the reverse which is to make the parentVc as the delegate and call the methods of textView subclass from it

how to hide keyboard on text view to return in swift3 [duplicate]

I am using UITextfied while clicking on textfied keyboard appear but when i pressed the return key, keyboard is not disappearing. I used the following code:
func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
return true;
}
the method resignfirstresponder is not getting in function.
You can make the app dismiss the keyboard using the following function
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
Here is a full example to better illustrate that:
//
// ViewController.swift
//
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var myTextField : UITextField
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.myTextField.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
}
Code source: http://www.snip2code.com/Snippet/85930/swift-delegate-sample
The return true part of this only tells the text field whether or not it is allowed to return.
You have to manually tell the text field to dismiss the keyboard (or what ever its first responder is), and this is done with resignFirstResponder(), like so:
// Called on 'Return' pressed. Return false to ignore.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
No Delegate Needed
You can create an action outlet from the UITextField for the "Primary Action Triggered" and resign first responder on the sender parameter passed in:
#IBAction func done(_ sender: UITextField) {
sender.resignFirstResponder()
}
Super simple.
(Thanks to Scott Smith's 60-second video for tipping me off about this: https://youtu.be/v6GrnVQy7iA)
Add UITextFieldDelegate to the class declaration:
class ViewController: UIViewController, UITextFieldDelegate
Connect the textfield or write it programmatically
#IBOutlet weak var userText: UITextField!
set your view controller as the text fields delegate in view did load:
override func viewDidLoad() {
super.viewDidLoad()
self.userText.delegate = self
}
Add the following function
func textFieldShouldReturn(userText: UITextField!) -> Bool {
userText.resignFirstResponder()
return true;
}
with all this your keyboard will begin to dismiss by touching outside the textfield aswell as by pressing return key.
I hate to add the same function to every UIViewController.
By extending UIViewController to support UITextFieldDelegate, you can provide a default behavior of "return pressed".
extension UIViewController: UITextFieldDelegate{
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true;
}
}
When you create new UIViewController and UITextField, all you have to do is to write one line code in your UIViewController.
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
}
You can even omit this one line code by hooking delegate in Main.storyboard. (Using "ctrl" and drag from UITextField to UIViewController)
Simple Swift 3 Solution:
Add this function to your view controllers that feature a text field:
#IBAction func textField(_ sender: AnyObject) {
self.view.endEditing(true);
}
Then open up your assistant editor and ensure both your Main.storyboard is on one side of your view and the desired view controller.swift file is on the other. Click on a text field and then select from the right hand side utilities panel 'Show the Connection Inspector' tab. Control drag from the 'Did End on Exit' to the above function in your swift file. Repeat for any other textfield in that scene and link to the same function.
#RSC
for me the critical addition in Xcode Version 6.2 (6C86e) is in override func viewDidLoad()
self.input.delegate = self;
Tried getting it to work with the return key for hours till I found your post, RSC. Thank you!
Also, if you want to hide the keyboard if you touch anywhere else on the screen:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true);
}
To get automatic keyboard dismissal, I put this code inside one of the methods of my custom text field's class:
textField.addTarget(nil, action:"firstResponderAction:", forControlEvents:.EditingDidEndOnExit)
Substitute your outlet's name for textField.
Another way of doing this which mostly uses the storyboard and easily allows you to have multiple text fields is:
#IBAction func resignKeyboard(sender: AnyObject) {
sender.resignFirstResponder()
}
Connect all your text fields for that view controller to that action on the Did End On Exit event of each field.
Here's the Swift 3.0 update to peacetype's comment:
textField.addTarget(nil, action:Selector(("firstResponderAction:")), for:.editingDidEndOnExit)
I would sugest to init the Class from RSC:
import Foundation
import UIKit
// Don't forget the delegate!
class ViewController: UIViewController, UITextFieldDelegate {
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
#IBOutlet var myTextField : UITextField?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.myTextField.delegate = self;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.view.endEditing(true);
return false;
}
}
When the user taps the Done button on the text keyboard, a Did End On Exit event will be generated; at that time, we need to tell the text field to give up control so that the keyboard will go away. In order to do that, we need to add an action method to our controller class.
Select ViewController.swift add the following action method:
#IBAction func textFieldDoneEditing(sender: UITextField) {
sender.resignFirstResponder()}
Select Main.storyboard in the Project Navigator and bring up the connections inspector. Drag from the circle next to Did End On Exit to the yellow View Controller icon in the storyboard and let go. A small pop-up menu will appear containing the name of a single action, the one we just added. Click the textFieldDoneEditing action to select it and that's it.
Swift 3
Add this code below to your VC
//hide keyboard when user tapps on return key on the keyboard
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true);
return false;
}
Works for me
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(handleScreenTap(sender:)))
self.view.addGestureRecognizer(tap)}
then you use this function
func handleScreenTap(sender: UITapGestureRecognizer) {
self.view.endEditing(true)
}
Swift
Using optional function from UITextFieldDelegate.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.endEditing(false)
}
false means that field can be ask to resign. true – force resign.
Make sure that your textField delegate is set to the view controller from which you are writing your textfield related code in.
self.textField.delegate = self
you can put this anywhere but not in a UIButton
func TextFieldEndEditing(text fiend name: UITextField!) -> Bool
{
return (false)
}
then you can put this code in a button(also for example):
self.view.endEditing(true)
this worked for me
In the view controller you are using:
//suppose you are using the textfield label as this
#IBOutlet weak var emailLabel: UITextField!
#IBOutlet weak var passwordLabel: UITextField!
//then your viewdidload should have the code like this
override func viewDidLoad() {
super.viewDidLoad()
self.emailLabel.delegate = self
self.passwordLabel.delegate = self
}
//then you should implement the func named textFieldShouldReturn
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// -- then, further if you want to close the keyboard when pressed somewhere else on the screen you can implement the following method too:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true);
}
you should connect the UITextfied with a delegate of view controller to make this function called
All in One Hide Keyboard and Move View on Keyboard Open: Swift 5
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(taped))
view.addGestureRecognizer(tap)
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
#objc func taped(){
self.view.endEditing(true)
}
#objc func KeyboardWillShow(sender: NSNotification){
let keyboardSize : CGSize = ((sender.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size)!
if self.view.frame.origin.y == 0{
self.view.frame.origin.y -= keyboardSize.height
}
}
#objc func KeyboardWillHide(sender : NSNotification){
let keyboardSize : CGSize = ((sender.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size)!
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += keyboardSize.height
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}

extending UITextView and triggering the delegate for onChange events

This code works and fires:
class ViewControllerDisplay: UIViewController, UITextViewDelegate {
//.....
let textView = MyUITextView(frame: CGRect(x:10, y:20, width:270, height:65))
textView.params["dataname"] = _dataname
textView.delegate = self
view.addSubview(textView)
func textViewDidChange(_ textView: UITextView) {
print("YAAAA" + textView.text);
}
however this does not fire
func textViewDidChange(_ textView: MyUITextView) {
print("YAAAA" + textView.text);
}
here is the MyUITextView code
import UIKit
class MyUITextView: UITextView{
var params: Dictionary<String, Any>
required init?(coder aDecoder: NSCoder) {
self.params = [:]
super.init(coder: aDecoder)
}
init(frame: CGRect) {
self.params = [:]
super.init(frame: frame, textContainer: nil)
}
}
so how do I extend the delegate to include MyUITextView in the delegate 'onChange'
The method textViewDidChange (textView: MyUITextView) was not called because in the protocol UITextViewDelegate that method is specified like func textViewDidChange ( textView: UITextView)
If you need to call specifically from the custom class MyUITextView, you need to write a protocol for this class, something like:
protocol MyUITextViewDelegate {
func myTextViewDidChange(_ textView: MyUITextView)
}
Add a field with type MyUITextViewDelegate? in class MyUITextView:
var myDelegate: MyUITextViewDelegate?
Initialize it for example in the viewDidLoad class of the ViewControllerDisplay class:
override func viewDidLoad() {
super.viewDidLoad()
...
textView.myDelegate = self
...
}
The class MyUITextView need to subscribe to the UITextViewDelegate protocol and implement the textViewDidChange (_ textView: UITextView) method in which our protocol is called from myDelegate if it exists:
class MyUITextView: UITextView, UITextViewDelegate {
...
func someInitMethod() {
delegate = self
}
...
func textViewDidChange(_ textView: UITextView) {
myDelegate?.myTextViewDidChange(self)
}
}
And finally, by signing the class ViewControllerDisplay on the protocol MyUITextViewDelegate and implement the necessary method:
class ViewControllerDisplay: UIViewController, MyUITextViewDelegate {
...
func textViewDidChange(_ textView: MyUITextView) {
print("YAAAA" + textView.text);
}
}
ok I figured it out by casting
func textViewDidChange(_ textView: UITextView) {
if let sender = textView as? MyUITextView {
let dataname = sender.params["dataname"] as? String ?? ""
print("MyUITextView: dataname" + dataname + " = " + sender.text!)
}
}

How to hide a label for specific text field input?

I´ve created a Xcode project with just one button, one text field and one label. I want to make the label only visible, when the text field input is "test123" or the button gets pressed. The part with the button works well, but no matter what i type in the textfield, the label stays hidden. Anyone help? This is my current code:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var Label: UILabel!
#IBOutlet weak var Examplefield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Label.hidden = true
Examplefield.resignFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func ButtonPressed(sender: UIButton) {
Label.hidden = false
}
func textFieldDidEndEditing(textField: UITextField) {
if Examplefield.text == "test123" {
Label.hidden = false
}
else {
Label.hidden = true
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
return true
}
}
The simplest solution is probably to connect the “Editing Changed” event of the text field to an action in your view controller:
The text field fires the “Editing Changed” event whenever the user changes the contents of the field. You don't have to set the delegate or register for a notification.
There are also “Editing Did End” and “Did End on Exit” events if you want to wait until the user exits the field.
You need to implement the shouldChangeCharactersInRange method from the UITextFieldDelegate in order to check if the string is the same when the text changes:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if (string == "test123") {
self.Label.hidden = false
} else {
self.Label.hidden = true
}
return true
}
Using shouldChangeCharactersInRange works well, but another option would be using the textFieldDidChange NSNotification.
In your viewDidLoad, register for the notification:
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("textFieldDidChange:"), name: "UITextFieldTextDidChangeNotification", object: nil)
Then define the appropriate method:
func textFieldDidChange(notification: NSNotification) {
self.label.hidden = (self.textField.text == "test123")
}
Use UITextField Delegate method
- (void)textFieldDidBeginEditing:(UITextField *)textField{
// your condition
}

How to hide keyboard in swift on pressing return key?

I am using UITextfied while clicking on textfied keyboard appear but when i pressed the return key, keyboard is not disappearing. I used the following code:
func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
return true;
}
the method resignfirstresponder is not getting in function.
You can make the app dismiss the keyboard using the following function
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
Here is a full example to better illustrate that:
//
// ViewController.swift
//
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var myTextField : UITextField
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.myTextField.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
}
Code source: http://www.snip2code.com/Snippet/85930/swift-delegate-sample
The return true part of this only tells the text field whether or not it is allowed to return.
You have to manually tell the text field to dismiss the keyboard (or what ever its first responder is), and this is done with resignFirstResponder(), like so:
// Called on 'Return' pressed. Return false to ignore.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
No Delegate Needed
You can create an action outlet from the UITextField for the "Primary Action Triggered" and resign first responder on the sender parameter passed in:
#IBAction func done(_ sender: UITextField) {
sender.resignFirstResponder()
}
Super simple.
(Thanks to Scott Smith's 60-second video for tipping me off about this: https://youtu.be/v6GrnVQy7iA)
Add UITextFieldDelegate to the class declaration:
class ViewController: UIViewController, UITextFieldDelegate
Connect the textfield or write it programmatically
#IBOutlet weak var userText: UITextField!
set your view controller as the text fields delegate in view did load:
override func viewDidLoad() {
super.viewDidLoad()
self.userText.delegate = self
}
Add the following function
func textFieldShouldReturn(userText: UITextField!) -> Bool {
userText.resignFirstResponder()
return true;
}
with all this your keyboard will begin to dismiss by touching outside the textfield aswell as by pressing return key.
I hate to add the same function to every UIViewController.
By extending UIViewController to support UITextFieldDelegate, you can provide a default behavior of "return pressed".
extension UIViewController: UITextFieldDelegate{
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true;
}
}
When you create new UIViewController and UITextField, all you have to do is to write one line code in your UIViewController.
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
}
You can even omit this one line code by hooking delegate in Main.storyboard. (Using "ctrl" and drag from UITextField to UIViewController)
Simple Swift 3 Solution:
Add this function to your view controllers that feature a text field:
#IBAction func textField(_ sender: AnyObject) {
self.view.endEditing(true);
}
Then open up your assistant editor and ensure both your Main.storyboard is on one side of your view and the desired view controller.swift file is on the other. Click on a text field and then select from the right hand side utilities panel 'Show the Connection Inspector' tab. Control drag from the 'Did End on Exit' to the above function in your swift file. Repeat for any other textfield in that scene and link to the same function.
#RSC
for me the critical addition in Xcode Version 6.2 (6C86e) is in override func viewDidLoad()
self.input.delegate = self;
Tried getting it to work with the return key for hours till I found your post, RSC. Thank you!
Also, if you want to hide the keyboard if you touch anywhere else on the screen:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true);
}
To get automatic keyboard dismissal, I put this code inside one of the methods of my custom text field's class:
textField.addTarget(nil, action:"firstResponderAction:", forControlEvents:.EditingDidEndOnExit)
Substitute your outlet's name for textField.
Another way of doing this which mostly uses the storyboard and easily allows you to have multiple text fields is:
#IBAction func resignKeyboard(sender: AnyObject) {
sender.resignFirstResponder()
}
Connect all your text fields for that view controller to that action on the Did End On Exit event of each field.
Here's the Swift 3.0 update to peacetype's comment:
textField.addTarget(nil, action:Selector(("firstResponderAction:")), for:.editingDidEndOnExit)
I would sugest to init the Class from RSC:
import Foundation
import UIKit
// Don't forget the delegate!
class ViewController: UIViewController, UITextFieldDelegate {
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
#IBOutlet var myTextField : UITextField?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.myTextField.delegate = self;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.view.endEditing(true);
return false;
}
}
When the user taps the Done button on the text keyboard, a Did End On Exit event will be generated; at that time, we need to tell the text field to give up control so that the keyboard will go away. In order to do that, we need to add an action method to our controller class.
Select ViewController.swift add the following action method:
#IBAction func textFieldDoneEditing(sender: UITextField) {
sender.resignFirstResponder()}
Select Main.storyboard in the Project Navigator and bring up the connections inspector. Drag from the circle next to Did End On Exit to the yellow View Controller icon in the storyboard and let go. A small pop-up menu will appear containing the name of a single action, the one we just added. Click the textFieldDoneEditing action to select it and that's it.
Swift 3
Add this code below to your VC
//hide keyboard when user tapps on return key on the keyboard
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true);
return false;
}
Works for me
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(handleScreenTap(sender:)))
self.view.addGestureRecognizer(tap)}
then you use this function
func handleScreenTap(sender: UITapGestureRecognizer) {
self.view.endEditing(true)
}
Swift
Using optional function from UITextFieldDelegate.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.endEditing(false)
}
false means that field can be ask to resign. true – force resign.
Make sure that your textField delegate is set to the view controller from which you are writing your textfield related code in.
self.textField.delegate = self
you can put this anywhere but not in a UIButton
func TextFieldEndEditing(text fiend name: UITextField!) -> Bool
{
return (false)
}
then you can put this code in a button(also for example):
self.view.endEditing(true)
this worked for me
In the view controller you are using:
//suppose you are using the textfield label as this
#IBOutlet weak var emailLabel: UITextField!
#IBOutlet weak var passwordLabel: UITextField!
//then your viewdidload should have the code like this
override func viewDidLoad() {
super.viewDidLoad()
self.emailLabel.delegate = self
self.passwordLabel.delegate = self
}
//then you should implement the func named textFieldShouldReturn
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// -- then, further if you want to close the keyboard when pressed somewhere else on the screen you can implement the following method too:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true);
}
you should connect the UITextfied with a delegate of view controller to make this function called
All in One Hide Keyboard and Move View on Keyboard Open: Swift 5
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(taped))
view.addGestureRecognizer(tap)
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
#objc func taped(){
self.view.endEditing(true)
}
#objc func KeyboardWillShow(sender: NSNotification){
let keyboardSize : CGSize = ((sender.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size)!
if self.view.frame.origin.y == 0{
self.view.frame.origin.y -= keyboardSize.height
}
}
#objc func KeyboardWillHide(sender : NSNotification){
let keyboardSize : CGSize = ((sender.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size)!
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += keyboardSize.height
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}

Resources