How to Move to the Previous Uitextfield If the "Backspace" Button Is Pressed and the Text Field Is Blank and in Swift 4

textfield backspace action identify when textfield is empty?

followed by @Marmik Shah and @Prashant Tukadiya answer here I add my answer , for quick answer I taken the some code from here

step 1 :

create the IBOutletCollection for your all textfields as well as don't forget to set the tag in all textfields in the sequence order, for e.g [1,2,3,4,5,6]

class ViewController: UIViewController{

@IBOutlet var OTPTxtFields: [MyTextField]! // as well as set the tag for textfield in the sequence order

override func viewDidLoad() {
super.viewDidLoad()

//change button color and other options
OTPTxtFields.forEach { $0.textColor = .red; $0.backspaceTextFieldDelegate = self }
OTPTxtFields.first.becomeFirstResponder()
}

step 2 :

in your current page UITextField delegate method

extension ViewController : UITextFieldDelegate, MyTextFieldDelegate {

func textFieldDidEnterBackspace(_ textField: MyTextField) {
guard let index = OTPTxtFields.index(of: textField) else {
return
}

if index > 0 {
OTPTxtFields[index - 1].becomeFirstResponder()
} else {
view.endEditing(true)
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newString = ((textField.text)! as NSString).replacingCharacters(in: range, with: string)

if newString.count < 2 && !newString.isEmpty {
textFieldShouldReturnSingle(textField, newString : newString)
// return false
}

return newString.count < 2 || string == ""
//return true
}
override public func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(copy(_:)) || action == #selector(paste(_:)) {
return false
}

return true
}
func textFieldShouldReturnSingle(_ textField: UITextField, newString : String)
{
let nextTag: Int = textField.tag + 1
textField.text = newString
let nextResponder: UIResponder? = textField.superview?.viewWithTag(nextTag)
if let nextR = nextResponder
{
// Found next responder, so set it.

nextR.becomeFirstResponder()
}
else
{
// Not found, so remove keyboard.
textField.resignFirstResponder()
callOTPValidate()
}
}

}

Step 3:

create the textfield class for access the backward function

class MyTextField: UITextField {
weak var myTextFieldDelegate: MyTextFieldDelegate?

override func deleteBackward() {
if text?.isEmpty ?? false {
myTextFieldDelegate?.textFieldDidEnterBackspace(self)
}

super.deleteBackward()
}

}

protocol MyTextFieldDelegate: class {
func textFieldDidEnterBackspace(_ textField: MyTextField)
}

step - 4

finally follow the @Marmik Shah answer for custom class for your UITextField

Sample Image

Step 5

get the values from each textfield use this

func callOTPValidate(){
var texts: [String] = []
OTPTxtFields.forEach { texts.append($0.text!)}
sentOTPOption(currentText: texts.reduce("", +))

}

func sentOTPOption(currentText: String) {
print("AllTextfieldValue == \(currentText)")
}

Detect backspace Event in UITextField

Swift 4.2

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")
}
}
return true
}

Older Swift version

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let char = string.cStringUsingEncoding(NSUTF8StringEncoding)!
let isBackSpace = strcmp(char, "\\b")

if (isBackSpace == -92) {
println("Backspace was pressed")
}
return true
}

Detect backspace in empty UITextField

This may be a long shot but it could work. Try setting the text field's text to a zero width space character \u200B. When backspace is pressed on a text field that appears empty, it will actually delete your space. Then you can just reinsert the space.

May not work if the user manages to move the caret to the left of the space.

Detect backspace in empty UITextField

This may be a long shot but it could work. Try setting the text field's text to a zero width space character \u200B. When backspace is pressed on a text field that appears empty, it will actually delete your space. Then you can just reinsert the space.

May not work if the user manages to move the caret to the left of the space.

Pressing Backspace/Delete in TextField iOS

Try do it like this:

//Get new length of the text after input
let newLength = (textField.text ?? "").count + string.count - range.length
if newLength == 0 {
//Go back prev textfield if new length is 0
}

To overcome the issue where the shouldChangeCharactersIn won't get called on empty field, simply carry the last character user input from last textfield to the next, so user will never have an empty field aside from the first textfield.

Another way is add a space character by default for each textfield and detect around it but it seems to be more annoying to dealt with.

Completely disable 'backspace' being pressed Swift

You need to simply implement textView(_:shouldChangeTextIn:replacementText:) and check for empty replacementText.

Empty replacementText == backspace pressed

If the text is Empty 1return false. Elsereturn true`.

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text.isEmpty {
return false
}
return true
}


Related Topics



Leave a reply



Submit