inputAccessoryView not showing above keyboard - ios

Problem relates to this.
I'm trying to use a custom view that I made that has two TextField inputs and a button, I made it using IB its xib, I've placed it in my story board and have it set to be at the bottom of my view.
The problem comes in when I want to make ContactInfoView the keyboards accessory view.
class ViewController: UIViewController, UITextViewDelegate {
#IBOutlet var cameraPreview: UIView!
#IBOutlet weak var ContactInfoView: KeyboardAccessoryView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//cameraPreviewLayer!.frame = cameraPreview.bounds
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillAppear"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide"), name: UIKeyboardWillHideNotification, object: nil)
ContactInfoView.NameInput.inputAccessoryView = ContactInfoView
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
// keyboard stuff
var accessoryView = KeyboardAccessoryView(frame: CGRectZero);
override var inputAccessoryView: KeyboardAccessoryView {
return accessoryView
}
override func becomeFirstResponder() -> Bool {
return true
}
override func canBecomeFirstResponder() -> Bool {
return true
}
func keyboardWillAppear() {
print("Keyboard appeared")
}
func keyboardWillHide() {
print("Keyboard hidden")
}
}
ContactInfoView.NameInput.inputAccessoryView = ContactInfoView isn't placing the view on top of the keyboard.
I fooled out around with the code and it started to crash relating to the link provided, But trying that solution didn't work either.

According to the comment in the UITextView.h file:
#property (nullable, readwrite, strong) UIView *inputView;
#property (nullable, readwrite, strong) UIView *inputAccessoryView;
Presented when object becomes first responder. If set to nil, reverts to following responder chain. If set while first responder, will not take effect until reloadInputViews is called.
You should call reloadInputViews method after setting input.. property.

Yes, This Looks Little Tricky since everything seems fine and same as everyone and the Xcode Auto Suggestion and Completion Tools Helps you to complete the predicted "override" Functions..
Here Is A simple Mistakes that I made While Showing "inputAccessoryView"
I Entered Xcode Suggested Text For Completing "inputAccessoryView" And "inputAccessoryView" for Override Function.
But For Adding "override var inputAccessoryView: UIView?" Func its okay To Select from Xcode Suggestion / Auto Completion
override var inputAccessoryView: UIView? {
get {
return inputContainerView
}
}
For "override var canBecomeFirstResponder : Bool" you should make sure that
you type ": Bool" and not the "() -> Bool", Like I made mistakes couple of time.
So Please If you want You can type yourself or just Copy Below Code Paste in your Class Anywhere and it will work Smoothly.
override var inputAccessoryView: UIView? {
get {
let inputContainerView = UIView()
inputContainerView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 50)
inputContainerView.backgroundColor = UIColor.gray
let textfield = UITextField()
textfield.text = "asasfdfs df sdf sdf ds f"
textfield.frame = CGRect(x: 0, y: 0, width: inputContainerView.frame.size.width, height: 50)
inputContainerView.addSubview(textfield)
// You can add Any Other Objects Like UIButton, Image, Label //you want And Constraints too.
return inputContainerView
}
}
override var canBecomeFirstResponder : Bool {
return true
}

In the code above, you are assigning the property InputAccessoryView not the property inputAccessoryView. Case is important.
Assuming everything else is setup correctly, this should get it to work, but there is something I don't understand. Why is your text field/text view a property of your input accessory view? If NameInput is a subview of ContactInfoView, then setting ContactInfoView.NameInput.inputAccessoryView will not work.

Related

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
}

(Xcode 8 Swift 3). Using Custom Keyboard Extension with a particular Text Field

Since standard Number Pad keyboard has "empty" button, but doesn't have "+/-" button, I decided to create my own Keyboard Extension. I've done it.
But I don't know how to link (and invoke) it with a particular Text Field while other Text Fields using usual keyboards.
Is there any opportunity to apply custom keyboardType like my own custom Keyboard?
I found solution based on simular question: How to input text using the buttons of an in-app custom keyboard
import UIKit
protocol KeyboardDelegate: class {
func keyWasTapped(text: String)
}
class KeyboardView: UIView {
// This variable will be set as the view controller so that
// the keyboard can send messages to the view controller.
weak var delegate: KeyboardDelegate?
// MARK:- keyboard initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeSubviews()
}
override init(frame: CGRect) {
super.init(frame: frame)
initializeSubviews()
}
func initializeSubviews() {
let xibFileName = "KeyboardView" // xib extention not included
let view = Bundle.main.loadNibNamed(xibFileName, owner: self, options: nil)?[0] as! UIView
self.addSubview(view)
view.frame = self.bounds
}
// MARK:- Button actions from .xib file
#IBAction func keyTapped(_ sender: UIButton) {
// When a button is tapped, send that information to the
// delegate (ie, the view controller)
self.delegate?.keyWasTapped(text: sender.titleLabel!.text!) // could alternatively send a tag value
}
}
/* when error: "Could not load NIB in bundle"
Could not load NIB in bundle
Visit the properties of the .xib files in the file inspector ,the property "Target Membership" pitch on the select box ,then your xib file was linked with your target
*/
In main ViewController.swift
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, KeyboardDelegate {
#IBOutlet weak var text1: UITextField!
#IBOutlet weak var text2: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// initialize custom keyboard
let keyboardView = KeyboardView(frame: CGRect(x: 0, y: 0, width: 375, height: 165))
keyboardView.delegate = self // the view controller will be notified by the keyboard whenever a key is tapped
// replace system keyboard with custom keyboard
text1.inputView = keyboardView //accessoryView
text1.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// required method for keyboard delegate protocol
func keyWasTapped(text character: String) {
if Int(character) != nil{
text1.insertText(character)
}
if character == "⌫" {
if !(text1.text?.isEmpty)! {
let beforeText = text1.text!
let truncated = beforeText.substring(to: beforeText.index(before: beforeText.endIndex))
text1.text = truncated
}
}
if character == "±" {
let beforeText = text1.text!
if var number = Int(beforeText) {
number = -number
text1.text = "\(number)"
}
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
/*
if (textField == self.text1) {
//textField.inputView = keyboardView
}
*/
}
}
I have coded a calculator for metric/imperial system. For that, I have coded my own keyboard, too.
I have set up the keyboard as UIButtons stacked within a Stack View.
The Buttons seem to be unknown for Xcode since I have just upgraded to Xcode 8 and the project is still in Swift 2.2.
Then I have set a UITextField and filled its text property using my buttons. This is for example the function for the Button 1 on my keyboard.
#IBOutlet weak var inputField: UITextField!
var numberStr:String = "0"
inputField.text = numberStr
#IBAction func oneKeyboardAction(sender: AnyObject) {
if numberStr == "0" {
numberStr = String(numberStr.characters.dropLast())
}
let newStr:String = numberStr + String("1")
numberStr = newStr
let dotToCommaString = newStr.stringByReplacingOccurrencesOfString(".", withString: ",")
inputField.text = dotToCommaString
}
Also I have deactivated user interaction with the TextField, so the "original Keyboard" will not show.
Edit
Like mentioned in the comment section and to have my answer better fit your needs. You could set my custom keyboard into a UIView overlapping your UIViewController inside the Interface Builder. Set it as MyKeyboardView.hidden = true inside the viewDidLoad().
Then you have your TextField where you want the custom Keyboard to be visible instead of the system one:
func textFieldDidBeginEditing(_ textField: UITextField) {
if (textField == self.yourDesiredTextField) { //the one where you want to use the custom keyboard
MyKeyboardView.hidden = false
}
}
Then you add a gesture recognizer like that:
override func viewDidLoad() {
super.viewDidLoad()
MyKeyboardView.hidden = true
let tap = UITapGestureRecognizer(target: self, action: #selector(gesture))
tap.numberOfTapsRequired = 1
view.addGestureRecognizer(tap)
}
func gesture() {
UIView.animateWithDuration(0.2) {
self.MyKeyboardView.hidden = true
}
}
To have it little more smooth, I have added animateWithDuration when hiding the keyboard.

Reload/Update View In Swift

I'm busy making an app with an account page. I want that users can logon via that page and as soon as they have done so successfully that the page reloads to display their account information rather than the standard message stating that they have to logon to make use of the page.
However when I get sent back to the account page from logging on the view doesn't really update. So therefore I am wondering if I can't reload the view after certain buttons are pressed that can check again wether the user is logged on or not and deal accordingly.
if you want to trigger layouting or just drawing there is setNeedsLayout and setNeedsDisplay
There is no built-in method to reload custom data (on iOS)
so do a reload and inside a reload -- call setNeedsDisplay
import UIKit
protocol MyViewDelegate {
func viewString() -> String;
}
class MyView : UIView {
var myViewDelegate : MyViewDelegate?
private var str : String?
func reloadData() {
if myViewDelegate != nil {
str = myViewDelegate!.viewString()
}
self.setNeedsDisplay()
}
override func drawRect(rect: CGRect) {
UIColor.whiteColor().setFill()
UIRectFill(self.bounds)
if str != nil {
let ns = str! as NSString
ns.drawInRect(self.bounds, withAttributes: [NSForegroundColorAttributeName: UIColor.blueColor(), NSFontAttributeName: UIFont.systemFontOfSize(10)])
}
}
}
class ViewController: UIViewController, MyViewDelegate {
func viewString() -> String {
return "blabla"
}
var v : MyView!
override func viewDidLoad() {
super.viewDidLoad()
v = MyView(frame: self.view.bounds)
self.view.addSubview(v)
v.myViewDelegate = self;
}
override func viewWillAppear(animated: Bool) {
v.reloadData()
}
}
In Swift use this,
If you wants to reload the UIView present in the viewController just use NotificationCenter.
In ViewController class add this in viewWillAppear
override func viewWillAppear(_ animated: Bool) {
//Trigger notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "update"), object: nil)
}
In UIView class add Observer for the notification
required init?(coder aDecoder: NSCoder) {
//Add Observer
NotificationCenter.default.addObserver(self, selector: #selector(updateList), name: NSNotification.Name(rawValue: "update"), object: nil)
}
#objc func updateList(){
//write Reload data here......
tableView.reloadData()
}
The Swift have really advanced itself and for many people if they don't know we can refresh the whole view with just one simple line of code.
viewWillAppear(true)

Swift-Move view up when keyboard appears with constraints

I am using the following code from "Programming iOS 8". I have a subview with constraints that contains a simple textfield. This view has top and bottom to superview constraints, which I have outlets for. I have an outlet for the subview as well. The goal here is that when the keyboard appears, it pushes this subview up. I get an error on the line "let f = self.fr!.frame" Thread 1: EXC_BAD_INSTRUCTION. Does it have to do with needing to unwrap the optional? Could it be an issue with my constraints? Any help would be much appreciated. Thanks.
import UIKit
class ViewController: UIViewController {
#IBOutlet var topSpace: NSLayoutConstraint!
#IBOutlet var bottomSpace: NSLayoutConstraint!
#IBOutlet var slidingView: UIView!
var fr: UIView?
override func viewDidLoad() {
NSNotificationCenter.defaultCenter().addObserver(
self, selector: "keyboardShow:",
name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(
self, selector: "keyboardHide:",
name: UIKeyboardWillHideNotification, object: nil)
super.viewDidLoad()
}
func textFieldDidBeginEditing(tf: UITextField) {
self.fr = tf // keep track of the first responder
}
func textFieldShouldReturn(tf: UITextField) -> Bool {
tf.resignFirstResponder()
self.fr = nil
return true
}
func keyboardShow(n:NSNotification) {
let d = n.userInfo!
var r = (d[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue()
r = self.slidingView.convertRect(r, fromView:nil)
let f = self.fr!.frame
let y : CGFloat =
f.maxY + r.size.height - self.slidingView.bounds.height + 5
if r.origin.y < f.maxY {
self.topSpace.constant = -y
self.bottomSpace.constant = y
self.view.layoutIfNeeded()
}
}
func keyboardHide(n:NSNotification){
self.topSpace.constant = 0
self.bottomSpace.constant = 0
self.view.layoutIfNeeded()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
If I'm not mistaken, the keyboard shows before you start editing, so your self.fr is still nil when your keyboard is shown. Check to see if it's nil. It shouldn't have to do anything with the optional unwrapping. It only fails when you unwrap a null.

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