To preface, this problem has been solved using a couple of different methods - I'll leave the stack overflow post that has the solution here text
The problem deals with detecting when the "delete" or "backspace" button has been pressed on the iOS keyboard. I specifically want to be able to detect when the button has been pressed on an empty TextField
I've been stuck on integrating a solution and I think it's from lack of understanding some intermediary steps.
Here are the solutions that have been posed that I know can work.
The first is integrating this delegate function:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if let char = string.cString(using: String.Encoding.utf8) {
let isBackSpace = strcmp(char, "\\b")
if (isBackSpace == -92) {
print("Backspace was pressed") // Or prefrom some operation
}
}
return true
}
The second is to subclass the UITextfield Class and create an override function:
class MyTextField: UITextField {
override public func deleteBackward() {
if text == "" {
// do something when backspace is tapped/entered in an empty text field
}
// do something for every backspace
super.deleteBackward()
}
}
The specific functionality that I want to achieve is switching @FocuState Variables within a content view. So for example : If (Second) TextField().isEmpty and "delete" key is pressed, then FocusStateOne = true.
Here is a basic content view with a couple different TextFields:
struct ContentView: View {
@State private var textOne = ""
@State private var textTwo = ""
@FocusState private var oneFocus: Bool
var body: some View {
VStack {
TextField("",text: $textOne)
.padding()
.focused($oneFocus)
TextField("",text: $textTwo)
.padding()
// Detect if TextField is empty and if "delete" is pressed, then @FocusState var oneFocus = true
Text("Entered text: \(textOne)")
.padding()
Text("Entered text: \(textTwo)")
.padding()
}
}
}
I've tried subclassing, this makes the most sense to me, but I don't understand how the subclass with be able to conform to a view struct and communicate / change the variables within that view. It seems like I'd have to write some other kind of function that could communicate with the variables inside of the content view, but I'm unsure.
As far as delegates go, I understand the basics of what a delegate function is, but can't seem to figure out how I can implement it into a basic content view.
Most times I try either of these solutions I get Scope related issues, I think there is a lot I'm not understanding / doing correctly.
Of these two solutions, which one is better in the context of what I'm trying to do? I'm just a little lost on the "in-between" steps. I'm a complete beginner to Swift.
struct ContentView: View
with SwiftUITextField(...)
. Are you after a solution for SwiftUI? – Laicize