Swift 5 Custom Textfield Delegate not working - ios

Ever since I updated my Xcode and project to Swift 5,
I have this incredibly weird issue with specific textfields.
These text fields have a custom class to allow a response to a swipe action. They also have a special response to a standard touch. When the text field is touched, the textFieldShouldBeginEditing function suppresses the keyboard raise and instead launches a custom pull out value selection menu.
All was working perfectly until the update, where, whenever I start my Xcode up (after a day or two) and load my app, the textFieldShouldBeginEditing for these fields is never called!
What cures them (riduculously) is going to each View Controller that has one of these custom textfields - and making a single stroke edit to the page.
Then, when I reload, the textfields on that particular view are good again.
But the problem happens all over again, a few days later after I reload the app.
And I can't seem to replicate the problem by merely shutting down Xcode or even my computer. It seems it has to be shut down for some random amount of time or something.
...I don't know what causes this.
One other point - is that the IBOutlets for the custom selection pane is on a parent Class that is parent to all of these view controllers.
It would take a ton of writing to distribute all of the parent codes to all of the children view controllers.
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
var boolVal = true
switch textField.tag {
case 11: boolVal = false; launchSelection(textField)
case 12: boolVal = false; launchSelection(textField)
default: boolVal = true; shutThatStupidSideBar()
}
textFieldTag = textField.tag
return boolVal
}
func launchSelection(_ tf:UITextField) {
selectionPane.textfield = tf
switch tf.tag {
case 11: selectionPane.tableData = lm.retreiveList("provider") //11 = Owner
case 12: selectionPane.tableData = lm.retreiveList("\(currentSettings.defUnitsStrand)GaugeStrand") //12 = Strand Gauge
default: break
}
toggleSideBar()
}

Check UITextField delegate to UIViewController in storyboard
Add UITextFieldDelegate to viewController code like This:
class ViewController: UIViewController, UITextFieldDelegate
Use this sample code:
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
print("Test")
return true
}

Related

UITapGestureRecognizer on a text field not as expected

In my class I have 11 UITapGestureRecognizers in an array textViewRecognizer attached to 11 out of 100 UITextFields in an array boxArray. When a Textfield is tapped containing a UIGestureRecognizer it runs tappedTextView where I try to get the index of the first responder.
However, due to some weird ordering in how things are executed, the action function only gives me the first responder of the previous first responder to the one that was just tapped.
Also, I have to double tap to even select the text field I was going for! I need to use the tap function and not the text delegates so this has been a real headache.
I have...
#objc func tappedTextField(_ sender: UITapGestureRecognizer) {
for i in 0...99 {
if (boxArray[i]?.isFirstResponder)! {
if let index = boxArray.index(of: boxArray[i]) {
print(index)
break
}
}
}
}
in my viewDidLoad I have
for i in 0...10 {
textFieldTapRecognizer[i].addTarget(self, action: #selector(self.tappedTextField(_:)))
}
In my class I have
I want to set 11 out of 100 textFields to have this a tap recognizer depending on some conditions (I'm just going to use a regular for loop here)
for i in 0...10 {
boxArray[i]?.addGestureRecognizer(textFieldTapRecognizer[i])
}
Is there anyway I can get it to give me the actual first responder, after the tap was made?
Is there anyway to go around the double tap to select the text field that has a UITapGesture?
Any help is greatly appreciated.
Edited: properly named functions
It sounds like you want to remove the automatic editing behavior on a UITextView. You can grab more control over that with the textViewShouldBeginEditing(_ textView: UITextView) -> Bool UITextViewDelegate method, documented here.
If you return false for that method, this should avoid needing a double tap to get to your gesture recognizer. Depending on your use case, you can then "allow" the tap to go to the text view by returning true for the textView you want to be actually edited.
While I'm not 100% clear on the first responder part of your question, since the textView won't be grabbing first responder if it's not starting it's editing mode, this should address that concern I believe. Good luck!
I would add a Tag to my UITextView and set the UITextViewDelegate to my ViewController.
Then I would add the following Delegate method:
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
print("Textview tag: ", textView.tag)
return false
}

How to move one text field to another using keyboard return key in swift3 ios

By this img with done btn to move at next textfield (https://i.stack.imgur.com/cDHlh.jpg)
I doubt if you can do that with the 'Done' button, but you may achieve that with the return key by
Make your class a UITextField Delegate
class VC: UIVIewController, UITextFieldDelegate
In your ViewDidLoad method do this -
textField1.becomeFirstResponder()
So that when user comes in this screen the 1st textfield will directly become active(not the right word but using this word for lack of better alternative)
And when you need it to move to the next textfield when he presses return,
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField1.resignFirstResponder()
if (textField == textField1){
textField2.becomeFirstResponder()
}
else if (textField == textField2){
textField3.becomeFirstResponder()
}
return true
}
You may use a switch case too in the above delegate method. And as mentioned in the comment in the question, do go through the link and know how to properly ask questions, giving as much detail as possible.

The caret disappears or won't show up in UITextField

I'm having trouble with the caret of UITextfields.
Whenever I tap on the textfield the caret doesn't show, but otherwise the textfield is working properly. The problem is similar to the problem described here (already tried the solution written there as well).
I noticed that whenever I load a viewcontroller and tap on a textfield (or programatically make it the first responder) it does show a caret, but as soon as I tap another textfield or make a textfield resign its first responder status no textfield will show its caret anymore (unless I go back and reload the viewcontroller again).
Got no clue as of why this is happening. I am using a custom font throughout the app. But I'm not sure if that's what making the caret disappear, as I've used custom fonts before with no problem whatsoever.
EDIT:
I think I've at least found why the problem occurs. It is related to me overriding the becomeFirstResponder and resignFirstResponder.
My code looks like:
extension UITextField {
open override func becomeFirstResponder() -> Bool {
let willBecomeResponder = super.becomeFirstResponder()
if willBecomeResponder {
backgroundColor = .red
layer.borderColor = .blue
}
return willBecomeResponder
}
open override func resignFirstResponder() -> Bool {
let willResignResponder = super.resignFirstResponder()
if willResignResponder {
backgroundColor = .blue
layer.borderColor = .red
}
return willResignResponder
}
}
Overriding those methods in the extension makes the caret disappear.
I'm thinking this most likely happens because UITextField itself does some...'caret-management' in it's own implementation of those methods.
More so because even return super.becomeFirstResponder() and no custom code in the overridden method makes the caret disappear.
My question therefore is; how can one solve this problem without making a custom UITextField subclass?
Calling super obviously just calls the UIResponder's implementation, but the docs specifically mention:
becomeFirstResponder()
You can override this method in your custom responders to update your object's state or perform some action such as highlighting the selection. If you override this method, you must call super at some point in your implementation.
So I need to call super I guess.
Alright I solved my problem by overriding isFirstResponder and altering the textfield based on the super.isFirstResponder there.
Looks like:
open override var isFirstResponder: Bool {
get {
let responder = super.isFirstResponder
backgroundColor = (responder) ? .red : .blue
layer.borderColor = (responder) ? .blue : .red
return responder
}
}
I did noticed a lot of calls being sent to isFirstResponder, so maybe this isn't the most efficient way (if altering the textfield is a heavy op).

Why call method to resignFirstResponder from textFieldShouldBeginEditing?

I am trying to understand delegate methods in general, and specifically how to dismiss a UIDatePicker that popovers from a text field.
According to the documentation, textFeildShouldBeginEditing returns true 'if an editing session should be initiated; otherwise, false to disallow editing.'
Why would I then tell the app to resignFirstResponder, which is meant to hide the keyboard / date picker (as in several examples on stackoverflow and noobie tutorials)?
What I don't understand is: if it should begin editing, why then hide the input devise? Obviously, I am misunderstanding one or both concepts.
func resign() {
dobTextField.resignFirstResponder()
nameTextField.resignFirstResponder()
println("resign gets printed, but the date picker is still visible!?!")
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if (textField === dobTextField) {
resign() // but should begin editing, oder?!?
}
In the examples you cite, the textField is being used to display a date. When the user selects this field, the app designers want the UIDatePicker to be displayed instead of the keyboard. Hence they call resignFirstResponder to hide the keyboard. At the same time, they display the date picker.
ResignFirstResponder will not hide the date picker, so the "input device" (for this field) will still be available.
Also, note that in one case the developer has used textFieldShouldBeginEditing, and returns false because they are providing the date picker. In the other case the developer uses textFieldDidBeginEditing (which has no return value).
you should resign only the textfield not affected:
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if textField == dobTextField {
nameTextField.resignFirstResponder()
} else if textField == nameTextField {
dobTextField.resignFirstResponder()
}
return true
}
this way you are resiging first responder only on the textfields that should not currently be edited. this helps if for some reason you accidentally have 2 textfields (or more) assigned first responder causing conflicts with multiple keyboards/datepickers and such.

IOS Dismiss/Show keyboard without Resigning First Responder

My application is used with a barcode scanner connected via Bluetooth. When the scanner is connected you can double tap a button on the scanner to dismiss/show the on screen keyboard. 90% of the time the user will want the keyboard to be hidden as they will be scanning a barcode to input data. There are a few exceptions that I know of ahead of time that the keyboard will need to be enabled, I would like to save them the effort of pressing the scanner button to bring up the keyboard and instead force the keyboard to show up.
The scanner does not use resignfirstresponder to dismiss the keyboard, this is evident because the cursor is still visible and scanning a barcode will input data into the current text field.
Does anyone know how to dismiss/show the on screen keyboard without using resignfirstresponder?
For reference I am using this scanner http://ww1.socketmobile.com/products/bluetooth-scanners/how-to-buy/details.aspx?sku=CX2864-1336
To end editing completely in the view you can use the following
[self.view endEditing:YES];
This will remove the keyboard for you in the view.
For anyone still struggling with this, you can achieve this in Swift by making the inputView of the textfield equals UIView()
That is:
yourtextfield.inputview = UIView()
I ran into this today and have found a solution. The trick is to use a secondary text field that is off-screen or hidden with a custom empty inputView set and make that field become the first responder. That field captures text from the hardware scanner while the software keyboard hides.
However I got this working using a very similar approach and instead making the view controller itself the first responder as the scanning input view.
Example:
class SearchViewController: UIViewController, UIKeyInput {
let searchField = UITextField()
let softwareKeyboardHider = UIView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(searchField)
inputAssistantItem.leadingBarButtonGroups = []
inputAssistantItem.trailingBarButtonGroups = []
}
override var canBecomeFirstResponder: Bool {
return true
}
override var inputView: UIView? {
return softwareKeyboardHider
}
var hasText: Bool {
return searchField.hasText
}
func insertText(_ text: String) {
searchField.insertText(text)
}
func deleteBackward() {
searchField.deleteBackward()
}
}
Now, when you want to hide the software keyboard make SearchViewController the first responder.
To show the software keyboard make SearchViewController.searchField the first responder.

Resources