iOS/Swift: how to detect touch action on a UITextField - ios

I would like to detect the touch action on a UITextField.
It seems the "Touch Up Inside" action is not fired by touching inside the textfield.

It seems "Touch Up Inside" is not enabled for UITextField, but "Touch Down" works.
So the solution is as follows:
Swift 4.x
myTextField.addTarget(self, action: #selector(myTargetFunction), for: .touchDown)
#objc func myTargetFunction(textField: UITextField) {
print("myTargetFunction")
}
Swift 3.x
myTextField.addTarget(self, action: #selector(myTargetFunction), for: UIControlEvents.touchDown)
#objc func myTargetFunction(textField: UITextField) {
print("myTargetFunction")
}

Swift 4 and higher:
class ViewController: UIViewController, UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == myTextField {
print("You edit myTextField")
}
}
}
This is a delegate function.

here's Swfit:
and you don't need to use the "touchUpInside" just use the delegate methods like so:
Make your View controller a delegate:
class ViewController: UIViewController, UITextFieldDelegate{
func textFieldDidBeginEditing(textField: UITextField) -> Bool {
if textField == myTextField {
return true // myTextField was touched
}
}
Here's the other delegate methods:
protocol UITextFieldDelegate : NSObjectProtocol {
optional func textFieldShouldBeginEditing(textField: UITextField) -> Bool // return NO to disallow editing.
optional func textFieldDidBeginEditing(textField: UITextField) // became first responder
optional func textFieldShouldEndEditing(textField: UITextField) -> Bool // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
optional func textFieldDidEndEditing(textField: UITextField) // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
optional func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool // return NO to not change text
optional func textFieldShouldClear(textField: UITextField) -> Bool // called when clear button pressed. return NO to ignore (no notifications)
optional func textFieldShouldReturn(textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore.
}
from swift docs:
struct UIControlEvents : RawOptionSetType {
init(_ rawValue: UInt)
init(rawValue: UInt)
static var TouchDown: UIControlEvents { get } // on all touch downs
static var TouchDownRepeat: UIControlEvents { get } // on multiple touchdowns (tap count > 1)
static var TouchDragInside: UIControlEvents { get }
static var TouchDragOutside: UIControlEvents { get }
static var TouchDragEnter: UIControlEvents { get }
static var TouchDragExit: UIControlEvents { get }
static var TouchUpInside: UIControlEvents { get }
static var TouchUpOutside: UIControlEvents { get }
static var TouchCancel: UIControlEvents { get }
static var ValueChanged: UIControlEvents { get } // sliders, etc.
static var EditingDidBegin: UIControlEvents { get } // UITextField
static var EditingChanged: UIControlEvents { get }
static var EditingDidEnd: UIControlEvents { get }
static var EditingDidEndOnExit: UIControlEvents { get } // 'return key' ending editing
static var AllTouchEvents: UIControlEvents { get } // for touch events
static var AllEditingEvents: UIControlEvents { get } // for UITextField
static var ApplicationReserved: UIControlEvents { get } // range available for application use
static var SystemReserved: UIControlEvents { get } // range reserved for internal framework use
static var AllEvents: UIControlEvents { get }
}
UITextField doesn't respond to "touchUpInside" see to the right side, you'll find it's acceptable control events

Update For Swift 3
Here is the code for Swift 3:
myTextField.addTarget(self, action: #selector(myTargetFunction), for: .touchDown)
This is the function:
func myTargetFunction() {
print("It works!")
}

I referred to the UIControlEvents documentation from Apple and came up with the following:
First add UITextFieldDelegate to your class then,
textBox.delegate = self
textBox.addTarget(self, action: #selector(TextBoxOn(_:)),for: .editingDidBegin)
textBox.addTarget(self, action: #selector(TextBoxOff(_:)),for: .editingDidEnd)
with the following functions:
func TextBoxOff(_ textField: UITextField) {
code
}
}
func TextBox(_ textField: UITextField) {
code
}
}

For Swift 3.1:
1) Create a gesture recognizer:
let textViewRecognizer = UITapGestureRecognizer()
2) Add a handler to the recognizer:
textViewRecognizer.addTarget(self, action: #selector(tappedTextView(_:)))
3) Add the recognizer to your text view:
textView.addGestureRecognizer(textViewRecognizer)
4) Add the handler to your class:
func tappedTextView(_ sender: UITapGestureRecognizer) {
print("detected tap!")
}

To make this a little clearer these things need to be in place. I used this to make it so if a user entered something in an app of my own's credit textField anything in the debit textField is deleted.
UITextFieldDelegate needs to be declared in the View controller i.e class SecondViewController:
The detector functions func myDebitDetector func myCreditDetector need to be in the ViewController class.
put debit.addTarget and credit.addtarget inside view will appear.
#IBOutlet weak var debit: UITextField! and #IBOutlet weak var credit: UITextField! are textfields on the storyboard and connected to the viewController.
class SecondViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
#IBOutlet weak var credit: UITextField!
#IBOutlet weak var debit: UITextField!
func myDebitDetector(textfield: UITextField ){
print("using debit")
credit.text = ""
}
func myCreditDetector(textfield: UITextField) {
print("using cedit")
debit.text = ""
}
override func viewWillAppear(animated: Bool) {
debit.addTarget(self, action: "myDebitDetector:", forControlEvents: UIControlEvents.TouchDown)
credit.addTarget(self, action: "myCreditDetector:", forControlEvents: UIControlEvents.TouchDown)
....
}
}

Set the UITextField delegate to your view controller
Obj-C
textField.delegate = self;
Swift
textField.delegate = self
Implement the delegate method
Obj-c
-(void)textField:(UITextField*)textField didBeginEditing {
// User touched textField
}
Swift
func textFieldDidBeginEditing(textField: UITextField!) { //delegate method
}

Swift 3.0 Version:
textFieldClientName.addTarget(self, action: Selector(("myTargetFunction:")), for: UIControlEvents.touchDown)

Swift 4.2.
Try .editingDidEnd instead of .touchDown and delegate.
myTextField.addTarget(self, action: #selector(myTargetFunction), for: .editingDidEnd)
#objc func myTargetFunction(textField: UITextField) {
print("textfield pressed")
}

On xamarin.iOS i easy to use:
YourTextField.WeakDelegate = this;
[...]
[Export("textFieldDidBeginEditing:")]
public void TextViewChanged(UITextField textField)
{
if (YourTextField.Equals(textField))
IsYourTextFileFocused = true;
}

** Swift 4.0 + **
Use custom action like this
YourTextField.addTarget(self, action: #selector(myTargetFunction(_:)), for: .allEditingEvents)
#IBAction private func myTargetFunction(_ sender: Any) {
if let textField = sender as? UITextField {
// get textField here
}
}

Related

How to add target to UITextField in a class other than ViewController

I am trying to write a class that has a method which observe text changes on UITextField objects.
When in ViewController, code below works as intended:
class ViewController: UIViewController {
#IBOutlet weak var password: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.addTarget(view, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
}
#objc func textFieldDidChange(_ textField: UITextField) {
print(textField.text!)
}
}
So i wrote a class and put methods in it as below:
internal class ListenerModule: NSObject, UITextFieldDelegate {
internal func textWatcher(textField: UITextField!, view: UIViewController!) {
textField.delegate = self
textField.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
}
#objc internal func textFieldDidChange(_ textField: UITextField) {
print(textField.text!)
}
}
//And in ViewController,
...
ListenerModule().textWatcher(textField: password, view: self)
...
But it does not work.
How can i add target to a TextField in a class or a library?
I think it could be because you are not persisting with your ListenerModule object.
I believe you are doing this ListenerModule().textWatcher(textField: password, view: self) in some function so the scope of the object created is limited to that function.
You could do the following:
// Globally in your UIViewController subclass
var listenerModule: ListenerModule?
// Some set up function after text field is initialized
private func setup()
{
listenerModule = ListenerModule()
// Then call the text watcher, not sure why you pass the view,
// doesn't seem like you use it
listenerModule?.textWatcher(textField: password, view: self)
}
Give this a try and see if this solves your issue

Using #objc delegate methods with multiple arguments

I want to be able to pass multiple arguments to a #selector() method other than only the sender itself.
Say, I have a UITextField which has a UITapGestureRecognizer, and I want some other class to be the delegate of this UITapGestureRecognizer. I write a delegate protocol for it called SomeDelegateProcotol. However, I also want to pass the instance of the UITextField to the delegate upon tap. I figured things might look something like this:
// The delegate
class Delegate: SomeDelegateProcotol {
private let textField = TextField()
func handleTapFromView(_ sender: UITapGestureRecognizer, textField: UITextField) {
print("Hey! I should handle the tap from the user.")
}
init() {
textField.delegate = self
}
}
// The protocol
#objc protocol SomeDelegateProtocol {
#objc func handletapFromView(_ sender: UITapGestureRecognizer, textField: UITextField)
}
class TextField: UITextField {
weak var delegate: SomeDelegateProtocol?
override init(frame: CGSize) {
super.init(frame: frame)
...
let gestureRecognizer = UITapGestureRecognizer(target: delegate!,
action: #selector(delegate!.handleTapFromView(_:, textField:
self)))
}
}
However, this is not the right syntax, as handleTapFromView(_:, textField: self) is invalid. This raises the following questions to which I haven't found a solution yet:
What exactly means this syntax? (_:). I assume it's passing itself, but the UITapGestureRecognizer is not created yet?
How do I successfully pass the TextField instance to the delegate alongside the sender?
I would suggest keeping things as simple as this,
protocol SomeDelegateProtocol: class {
func handletapFromView(_ sender: UITapGestureRecognizer, textField: UITextField)
}
class TextField: UITextField {
weak var someDelegate: SomeDelegateProtocol?
override init(frame: CGRect) {
super.init(frame: frame)
let tap = UITapGestureRecognizer.init(target: self, action: #selector(tap(_:)))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
#objc private func tap(_ sender: UITapGestureRecognizer) {
self.someDelegate?.handletapFromView(sender, textField: self)
}
}

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
}
}

Swift: how to use UISwitch to control UITextField to be enabled or disabled with a delegate

In XCode 6.3.2, I have a UITextField:
#IBOutlet weak var uiswitchControlledTextField: UITextField!
I am now using a UISwitch (named mySwitch) to control its enabled or disabled state in the following way:
#IBOutlet weak var mySwitch: UISwitch!
mySwitch.addTarget(self, action: Selector("stateChanged:"), forControlEvents: UIControlEvents.ValueChanged)
//callback below:
func stateChanged(switchState: UISwitch) {
uiswitchControlledTextField.enabled = switchState.on
}
The above works well, however, I am looking to try if it would be possible to create a UITextFieldDelegate to control the above UITextField in the same way. So far, I have the following by implementing textFieldShouldBeginEditing, in which I wish to return false to disable the UITextField, but I don't know how to let the UISwitch dynamically return true or false from textFieldShouldBeginEditing
import Foundation
import UIKit
class SwitchControlledTextFieldDelegate: NSObject, UITextFieldDelegate {
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
return false; //do not show keyboard or cursor
}
}
In ViewController, I try to set
self.uiswitchControlledTextField.delegate = SwitchControlledTextFieldDelegate()
but it does not work as I wished. Any help would be appreciated.
self.uiswitchControlledTextField.delegate = SwitchControlledTextFieldDelegate()
The problem is that that line merely creates an instance of your SwitchControlledTextFieldDelegate class, which then immediately goes right back out of existence.
You need to use, as your text field delegate, some instance which already exists and which will persist - like, perhaps, your view controller!
(Xcode 7)
Use this:
override func viewDidLoad() {
super.viewDidLoad()
// Setting the delegate
self.textField3.delegate = self
self.editingSwitch.setOn(false, animated: false)
}
// Text Field Delegate Methods
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
return self.editingSwitch.on
}
#IBAction func toggleTheTextEditor(sender: AnyObject) {
if !(sender as! UISwitch).on {
self.textField3.resignFirstResponder()
}
}

Function not running when return pressed

I have a textfield, when something is typed in the textfield and "return" on the keyboard is pressed, the keyboard should hide. But it doesn't..
Here is the code I am using:
import UIKit
class EditTableViewController: UITableViewController, UITextFieldDelegate {
var product: Product?
#IBOutlet weak var productImageView: UIImageView!
#IBOutlet weak var ProductDescriptionTextView: UITextView!
#IBOutlet weak var productTitleLabel: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
println("loaded")
productImageView.image = product?.image
productTitleLabel.text = product?.title
ProductDescriptionTextView.text = product?.description
}
override func viewWillDisappear(animated: Bool) {
product?.title = productTitleLabel.text
product?.description = ProductDescriptionTextView.text
product?.image = productImageView.image!
}
func textFieldShouldReturn(textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore.
{
println("return")
return true
}
}
In the console I get "loaded", but when I press return in the textfield, I don't get "return"
how come?
You forgot to set the UITextField's delegate to your view controller (self)
productTitleLabel.delegate = self - also note that you should name your variables properly to avoid confusion (productTitleTextField instead of a 'Label' suffix)
Or, instead of doing it programmatically, you can do it in storyboard by Ctrl-dragging from your textView to the view controller in storyboard, and select delegate on the popup.
Then, let your view controller conform to UITextFieldDelegate protocol:
class EditTableViewController: UITableViewController, UITextFieldDelegate {
....
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == productTitleLabel {
textField.resignFirstResponder()
}
return true
}
}
In your viewDidLoad method you have to add:
productTitleLabel.delegate = self
And update your textFieldShouldReturn like this:
func textFieldShouldReturn(textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore.
{
productTitleLabel.resignFirstResponder()
return true
}
And It will hide your keyboard when return key pressed.

Resources