iOS: How do I make my UITextfield highlight when tapped? - ios

Do I have to do this with code or is there something in the inspector that I'm missing?

Unlike UIButton, a UITextField does not have a highlighted state. If you want to change the color of the textfield when it receives focus, you can use the UITextFieldDelegate's - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
This will be called when the control first receives focus. From there you can change the background and/or text color. Once focus leaves the control, you can use - (BOOL)textFieldShouldEndEditing:(UITextField *)textField to reset the colors.

In Swift 2, you can use the delegate functions like below,
class CustomTextField: UITextField, UITextFieldDelegate{
init(){
super.init(frame: CGRectMake(0, 0, 0, 0))
self.delegate = self // SETTING DELEGATE TO SELF
}
func textFieldDidBeginEditing(textField: UITextField) {
textField.backgroundColor = UIColor.greenColor() // setting a highlight color
}
func textFieldDidEndEditing(textField: UITextField) {
textField.backgroundColor = UIColor.whiteColor() // setting a default color
}
}

If you still want to be able to use other delegate functions in you ViewController, I recommend you to add this:
override weak var delegate: UITextFieldDelegate? {
didSet {
if delegate?.isKindOfClass(YourTextField) == false {
// Checks so YourTextField (self) doesn't set the textFieldDelegate when assigning self.delegate = self
textFieldDelegate = delegate
delegate = self
}
}
}
// This delegate will actually be your public delegate to the view controller which will be called in your overwritten functions
private weak var textFieldDelegate: UITextFieldDelegate?
class YourTextField: UITextField, UITextFieldDelegate {
init(){
super.init(frame: CGRectZero)
self.delegate = self
}
func textFieldDidBeginEditing(textField: UITextField) {
textField.backgroundColor = UIColor.blackColor()
textFieldDelegate?.textFieldDidBeginEditing?(textField)
}
func textFieldDidEndEditing(textField: UITextField) {
textField.backgroundColor = UIColor.whiteColor()
textFieldDelegate?.textFieldDidBeginEditing?(textField)
}
}
This way your view controller doesn't need to know that you have overwritted the delegate and you can implement UITextFieldDelegate functions in your view controller.
let yourTextField = YourTextField()
yourTextField.delegate = self

Related

Swift: recognize when UITextField is tapped

I am new to swift and have been stuck on this for hours. I am trying to recognize when a UITextField is tapped by the user, and call some function. For some reason I keep getting "unrecognized selector sent to instance".
Here is my attempt at a solution
and
Here is the error thrown
Any help is greatly appreciated!
Your selector is not pointing to the method! Try this instead:
textField.addTarget(self, action: #selector(ViewController.tapped(_:)), for: UIControlEvents.touchDown)
Also, instead of this approach you could also set ViewController as the delegate for textField and implement this:
extension ViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
print("tapped")
textField.backgroundColor = UIColor.blue
}
}
Use: action: #selector(ViewController.tapped())
Also, below that, add this: self.textField.delegate = self
you can simply perform you action in UITexFieldDelegate,
by making
myTextField.delegate = self
and use the method
optional public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{
//perform you action here
return true
}
instead of finding a way to get tap event you can use textFieldDidBeginEditing function:
class ViewController: UIViewController, UITextFieldDelegate
{
#IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self;
// Do any additional setup after loading the view, typically from a nib.
}
func textFieldDidBeginEditing(textField: UITextField) {
print("TextField did begin editing method called")
}
func textFieldDidEndEditing(textField: UITextField) {
print("TextField did end editing method called")
}
}

(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.

Try to get UITextField from subviews, but getting UITextfieldLabel

I have a view contain multiple UITextField.
So when keyboard pop up I loop through the view to find out which textfield is first responder.
I try to print out all the view class, it show UITextFieldLabel instead of UITextField, anyone know what is this? I want to find out which textfiled getting focus.
Here is the code I use.
extension UIView{
func firstResponder() -> UIView?{
if self.isFirstResponder()
{
return self
}
for view in self.subviews
{
if view.isFirstResponder()
{
return view
}
}
return nil
}
}
UITextField has a protocol to which your view can conform to. When a textfield is selected or edited, you will get that textfield in your delegate method.
class myView: UIView, UITextFieldDelegate {
var anExampleTextField: UITextField?
override init(frame: CGRect) {
super.init(frame: frame);
self.anExampleTextField.delegate = self
}
//if using interface builder
override func awakeFromNib() {
super.awakeFromNib()
self.anExampleTextField.delegate = self
}
func textFieldDidBeginEditing(textField: UITextField) {
//The selected textfield will be passed here.
}
}

Switching between Text fields on pressing return key in Swift

I'm designing an iOS app and I want that when the return key is pressed in my iPhone it directs me to the next following text field.
I have found a couple of similar questions, with excellent answers around but they all just happen to be in Objective-C and I'm looking for Swift code, now this is what I have up until now:
func textFieldShouldReturn(emaillabel: UITextField) -> Bool{
return true
}
It's placed in the file that's connected and controller to the UIView that contains the text fields, but I'm not sure if thats the right place.
Okay, so I tried this out and got this error:
//could not find an overload for '!=' that accepts the supplied arguments
func textFieldShouldReturn(textField: UITextField) -> Bool {
let nextTag: NSInteger = textField.tag + 1
// Try to find next responder
let nextResponder: UIResponder = textField.superview!.viewWithTag(nextTag)!
if (nextResponder != nil) {
// could not find an overload for '!=' that accepts the supplied arguments
// Found next responder, so set it.
nextResponder.becomeFirstResponder()
} else {
// Not found, so remove keyboard.
textField.resignFirstResponder()
}
return false // We do not want UITextField to insert line-breaks.
}
Make sure your UITextField delegates are set and the tags are incremented properly. This can also be done through the Interface Builder.
Here's a link to an Obj-C post I found: How to navigate through textfields (Next / Done Buttons)
class ViewController: UIViewController,UITextFieldDelegate {
// Link each UITextField (Not necessary if delegate and tag are set in Interface Builder)
#IBOutlet weak var someTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do the next two lines for each UITextField here or in the Interface Builder
someTextField.delegate = self
someTextField.tag = 0 //Increment accordingly
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Try to find next responder
if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else {
// Not found, so remove keyboard.
textField.resignFirstResponder()
}
// Do not add a line break
return false
}
}
Swift 5
You can easily switch to another TextField when clicking return key in keyboard.
First, Your view controller conforms to UITextFieldDelegate and add the textFieldShouldReturn(_:) delegate method in ViewController
Drag from TextField to ViewController in Interface Builder. Then select the delegate option. Note : Do this for all TextField
Create an IBOutlet for all TextFields
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var txtFieldName: UITextField!
#IBOutlet weak var txtFieldEmail: UITextField!
#IBOutlet weak var txtFieldPassword: UITextField!
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == txtFieldName {
textField.resignFirstResponder()
txtFieldEmail.becomeFirstResponder()
} else if textField == txtFieldEmail {
textField.resignFirstResponder()
txtFieldPassword.becomeFirstResponder()
} else if textField == txtFieldPassword {
textField.resignFirstResponder()
}
return true
}
}
I suggest that you should use switch statement in textFieldShouldReturn(_:).
// MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
switch textField {
case nameTextField:
phoneTextField.becomeFirstResponder()
case phoneTextField:
emailTextField.becomeFirstResponder()
case emailTextField:
descriptionTextField.becomeFirstResponder()
default:
textField.resignFirstResponder()
}
return false
}
This approach needs some changes in table views and collection views, but it's okay for simple forms I guess.
Connect your textFields to one IBOutletCollection, sort it by its y coordinate and in textFieldShouldReturn(_:) just jump to the next textfield until you reach the end:
#IBOutlet var textFields: [UITextField]!
...
textFields.sortInPlace { $0.frame.origin.y < $1.frame.origin.y }
...
func textFieldShouldReturn(textField: UITextField) -> Bool {
if let currentIndex = textFields.indexOf(textField) where currentIndex < textFields.count-1 {
textFields[currentIndex+1].becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return true
}
Or just look at sample project (xcode 7 beta 4)
Swift & Programmatically
class MyViewController: UIViewController, UITextFieldDelegate {
let textFieldA = UITextField()
let textFieldB = UITextField()
let textFieldC = UITextField()
let textFieldD = UITextField()
var textFields: [UITextField] {
return [textFieldA, textFieldB, textFieldC, textFieldD]
}
override func viewDidLoad() {
// layout textfields somewhere
// then set delegate
textFields.forEach { $0.delegate = self }
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let selectedTextFieldIndex = textFields.firstIndex(of: textField), selectedTextFieldIndex < textFields.count - 1 {
textFields[selectedTextFieldIndex + 1].becomeFirstResponder()
} else {
textField.resignFirstResponder() // last textfield, dismiss keyboard directly
}
return true
}
}
Caleb's version in Swift 4.0
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let nextField = self.view.viewWithTag(textField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return false
}
P.S. textField.superview? not working for me
I have tried many codes and finally this worked for me in Swift 3.0 Latest [March 2017]
The "ViewController" class should inherited the "UITextFieldDelegate" for making this code working.
class ViewController: UIViewController,UITextFieldDelegate
Add the Text field with the Proper Tag nuber and this tag number is used to take the control to appropriate text field based on incremental tag number assigned to it.
override func viewDidLoad() {
userNameTextField.delegate = self
userNameTextField.tag = 0
userNameTextField.returnKeyType = UIReturnKeyType.next
passwordTextField.delegate = self
passwordTextField.tag = 1
passwordTextField.returnKeyType = UIReturnKeyType.go
}
In the above code, the "returnKeyType = UIReturnKeyType.next" where will make the Key pad return key to display as "Next" you also have other options as "Join/Go" etc, based on your application change the values.
This "textFieldShouldReturn" is a method of UITextFieldDelegate controlled and here we have next field selection based on the Tag value incrementation
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else {
textField.resignFirstResponder()
return true;
}
return false
}
the easiest way to change to next text Field is this no need for long code
override func viewDidLoad() {
super.viewDidLoad()
emailTextField.delegate = self
passwordTextField.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == emailTextField {
passwordTextField.becomeFirstResponder()
}else {
passwordTextField.resignFirstResponder()
}
return true
}
I have a good solution for your question.
STEP:
1 - Set your return key from the storyboard.
2 - In your swift file.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField.returnKeyType == .next {
Email.resignFirstResponder()
Password.becomeFirstResponder()
} else if textField.returnKeyType == .go {
Password.resignFirstResponder()
self.Login_Action()
}
return true
}
3 - Don't forget to set the delegate of the Textfield.
Thank you :)
Just use becomeFirstResponder() method of UIResponder class in your textFieldShouldReturn method. Every UIView objects are UIResponder's subclasses.
if self.emaillabel.isEqual(self.anotherTextField)
{
self.anotherTextField.becomeFirstResponder()
}
You can find more information about becomeFirstResponder() method at Apple Doc's in here.
Swift 4.2
This is a More Generic and Easiest Solution, you can use this code with any amount of TextFields.
Just inherit UITextFieldDelegate and update the Textfield Tag according to the order and copy this function
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let txtTag:Int = textField.tag
if let textFieldNxt = self.view.viewWithTag(txtTag+1) as? UITextField {
textFieldNxt.becomeFirstResponder()
}else{
textField.resignFirstResponder()
}
return true
}
An alternative method for purists who don't like using tags, and wants the UITextField delegate to be the cell to keep the components separated or uni-directional...
Create a new protocol to link the Cell's and the TableViewController.
protocol CellResponder {
func setNextResponder(_ fromCell: UITableViewCell)
}
Add the protocol to your cell, where your TextField Delegate is also the cell (I do this in the Storyboard).
class MyTableViewCell: UITableViewCell, UITextFieldDelegate {
var responder: CellResponder?
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
responder?.setNextResponder(self)
return true
}
}
Make your TableViewController conform to the CellResponder protocol (i.e. class MyTableViewController: UITableViewController, CellResponder) and implement the method as you wish. I.e. if you have different cell types then you could do this, likewise you could pass in the IndexPath, use a tag, etc.. Don't forget to set cell.responder = self in cellForRow..
func setNextResponder(_ fromCell: UITableViewCell) {
if fromCell is MyTableViewCell, let nextCell = tableView.cellForRow(at: IndexPath(row: 1, section: 0)) as? MySecondTableViewCell {
nextCell.aTextField?.becomeFirstResponder()
} ....
}
No any special, here is my currently using to change the textFiled. So the code in ViewController looks good :). #Swift4
final class SomeTextFiled: UITextField {
public var actionKeyboardReturn: (() -> ())?
override init(frame: CGRect) {
super.init(frame: frame)
super.delegate = self
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("init(coder:) has not been implemented")
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.resignFirstResponder()
actionKeyboardReturn?()
return true
}
}
extension SomeTextFiled: UITextFieldDelegate {}
class MyViewController : UIViewController {
var tfName: SomeTextFiled!
var tfEmail: SomeTextFiled!
var tfPassword: SomeTextFiled!
override func viewDidLoad() {
super.viewDidLoad()
tfName = SomeTextFiled(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
tfName.actionKeyboardReturn = { [weak self] in
self?.tfEmail.becomeFirstResponder()
}
tfEmail = SomeTextFiled(frame: CGRect(x: 100, y: 0, width: 100, height: 100))
tfEmail.actionKeyboardReturn = { [weak self] in
self?.tfPassword.becomeFirstResponder()
}
tfPassword = SomeTextFiled(frame: CGRect(x: 200, y: 0, width: 100, height: 100))
tfPassword.actionKeyboardReturn = {
/// Do some further code
}
}
}
If you have a lot of textfield components my be it could be better to use an outlet collection, linking textfields and setting Return Key from interface builder
#IBOutlet var formTextFields: [UITextField]!
override func viewDidLoad() {
for textField in formTextFields {
textField.delegate = self
}
}
extension RegisterViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let componentIndex = formTextFields.firstIndex(of: textField) {
if textField.returnKeyType == .next,
componentIndex < (formTextFields.count - 1) {
formTextFields[componentIndex + 1].becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
}
return true
}
}
Swift 4+
This piece of code will help you.
class YOURClass: UITextFieldDelegate {
override func viewDidLoad() {
//delegate your textfield in here
choosenTextField1.delegate = self
choosenTextField2.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
switch textField.tag {
case 1:
choosenTextField1.becomeFirstResponder()
case 2:
choosenTextField2.becomeFirstResponder()
default:
break
}
return true
}
}
You can go with field tags. I think that's easier than other.
First of all you have enter code hereto give tag to your field.
On my code usernameField tag is 0 and passwordField tag is 1. And I check my tag. Then doing proccess.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField.tag == 0 {
passwordField.becomeFirstResponder()
} else if textField.tag == 1 {
self.view.endEditing(true)
loginFunc()
} else {
print("Hata var")
}
return false
}
If click return on username field, go password.
Or If you click return when password field, run login function to login.
The viewWithTag is a bad solution because the superview may have views with tags set. This is better:
public extension Collection where Element: Equatable {
func element(after element: Element) -> Element? {
guard let index = firstIndex(of: element) else { return nil }
let nextIndex = self.index(after: index)
return nextIndex < endIndex ? self[nextIndex] : nil
}
}
class Controller: UIViewController {
#IBOutlet weak var firstNameTextField: UITextField!
#IBOutlet weak var lastNameTextField: UITextField!
#IBOutlet weak var companyTextField: UITextField!
private lazy var primaryTextFields: [UITextField] = {
[firstNameTextField, lastNameTextField, companyTextField]
}()
override func viewDidLoad() {
super.viewDidLoad()
primaryTextFields.forEach { $0.delegate = self }
}
}
extension Controller: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let next = primaryTextFields.element(after: textField) {
next.becomeFirstResponder()
} else if primaryTextFields.contains(textField) {
textField.resignFirstResponder()
}
return true
}
}

How to hide the keyboard when I press return key in a UITextField?

Clicking in a textfield makes the keyboard appear.
How do I hide it when the user presses the return key?
First make your file delegate for UITextField
#interface MYLoginViewController () <UITextFieldDelegate>
#end
Then add this method to your code.
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
Also add self.textField.delegate = self;
In viewDidLoad declare:
[yourTextField setDelegate:self];
Then, include the override of the delegate method:
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
Try this in Swift,
Step 1: Set delegate as self to your textField
textField.delegate = self
Step 2: Add this UITextFieldDelegate below your class declaration,
extension YourClassName: UITextFieldDelegate {
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
In swift do like this:
First in your ViewController implement this UITextFieldDelegate
For eg.
class MyViewController: UIViewController, UITextFieldDelegate {
....
}
Now add a delegate to a TextField in which you want to dismiss the keyboard when return is tapped either in viewDidLoad method like below or where you are initializing it.
For eg.
override func viewDidLoad() {
super.viewDidLoad()
myTextField.delegate = self
}
Now add this method.
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
Swift 4
Set delegate of UITextField in view controller, field.delegate = self, and then:
extension ViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// don't force `endEditing` if you want to be asked for resigning
// also return real flow value, not strict, like: true / false
return textField.endEditing(false)
}
}
set delegate of UITextField, and over ride, textFieldShouldReturn method, in that method just write following two lines:
[textField resignFirstResponder];
return YES;
that's it. Before writing a code dont forget to set delegate of a UITextField and set Return key type to "Done" from properties window.(command + shift + I).
Try this,
[textField setDelegate: self];
Then, in textField delegate method
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
Define this class and then set your text field to use the class and this automates the whole hiding keyboard when return is pressed automatically.
class TextFieldWithReturn: UITextField, UITextFieldDelegate
{
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
self.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
textField.resignFirstResponder()
return true
}
}
Then all you need to do in the storyboard is set the fields to use the class:
You can connect "Primary Action Triggered" (right click on UITextField) with an IBAction and you can resign first responder (without delegation). Example
(Swift 4):
#IBAction func textFieldPrimaryAction(_ sender: UITextField) {
sender.resignFirstResponder()
...
}
Ok, I think for a novice things might be a bit confusing. I think the correct answer is a mix of all the above, at least in Swift4.
Either create an extension or use the ViewController in which you'd like to use this but make sure to implement UITextFieldDelegate. For reusability's sake I found it easier to use an extension:
extension UIViewController : UITextFieldDelegate {
...
}
but the alternative works as well:
class MyViewController: UIViewController {
...
}
Add the method textFieldShouldReturn (depending on your previous option, either in the extension or in your ViewController)
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return textField.endEditing(false)
}
In your viewDidLoad method, set the textfield's delegate to self
#IBOutlet weak var myTextField: UITextField!
...
override func viewDidLoad() {
..
myTextField.delegte = self;
..
}
That should be all. Now, when you press return the textFieldShouldReturn should be called.
If you want to hide the keyboard for a particular keyboard use
[self.view resignFirstResponder];
If you want to hide any keyboard from view use [self.view endEditing:true];
[textField resignFirstResponder];
Use this

Resources