Allow Backspace with character set - ios

I am having trouble deleting in my text field. So I have a text field for a person name only allowing letters. But when I hit the delete or backspace it doesn't seem to work. This is what my code looks like.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let set = CharacterSet.letter
return (string.rangeOfCharacter(from: set) != nil)
}
I am not sure why the backspace/delete is not working.

When the user taps the backspace, string will be the empty string. So rangeOfCharacter will be nil so your code returns false preventing the backspace from working.
Try this:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return string.isEmpty || string.rangeOfCharacter(from: CharacterSet.letter) != nil
}

When you tap the backspace check for backspace code and return false if rangeOfCharacter for your regular expression is nil else return true.
Try this:
let char = text.cString(using: String.Encoding.utf8)!
let isBackSpace = strcmp(char, "\\b")
if (isBackSpace == -92) {
}else if text.range(of: kRangeWithoutSpace, options:.regularExpression) == nil {
return false
}

Related

iOS 13 Crash with SwipeKeyboard and textfield:shouldChangeCharactersIn:

In iOS 13, when implementing shouldChangeCharactersIn via the UITextfieldDelegate, the application crashes when using the swiping keyboard.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let text = textField.text as NSString? {
let txtAfterUpdate = text.replacingCharacters(in: range, with: string)
textField.text = txtAfterUpdate
}
return false
}
Is this an Apple bug?
I was able to reproduce this - if you mutate the state of the text on a UITextField during swipe entry - and only during swipe entry, it'll attempt to reinsert the swiped content (even if you return false), which retriggers your delegate event, which kicks off the recursive cycle.
It's a bit of a hack but you could catch it with something like
private var lastEntry: String?
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.count > 1 && string == lastEntry { // implies we're swiping or pasting
print("Caught unwanted recursion")
return
}
lastEntry = string
if let text = textField.text as NSString? {
let txtAfterUpdate = text.replacingCharacters(in: range, with: string)
textField.text = txtAfterUpdate
}
return false
}
It'll stop users from pasting/swiping the same thing twice in a row, but at least it'll let them swipe while Apple fixes their problem.
I used UIPasteboard to identify when the user is pasting and then leave the text as the user entered using the swipe like this:
public func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
//check if the user used swipe keyboard
if string.count > 1 && string != UIPasteboard.general.string ?? "" {
return true
}
//do the text treatment
return false
}
I also realized that the TextField only accepts static strings when using swipe keyboard.
Hope it Helps.
Before setting text you can reset delegate and after set it to self again.
But this solution has one problem if textfield is empty - text will be doubled.
Му code example:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentText: String = textField.text ?? ""
if #available(iOS 13, *) {
textField.delegate = nil
let resultText = editedText
textField.text = resultText
if currentText.isEmpty, textField.text != resultText {
textField.text = resultText
}
textField.delegate = self
} else {
textField.text = input.result
}
return false
}

How to limit the text field to be able to enter only decimal digits?

I have the app for Celectial navigation calculations, I have converted in code textField.text to Double, but some times app crashing if user input some fields like "1.0" and some like "1", in result app crashing because can't deduct Int and Double, to be sure I want to restrict user to input only decimal digits "1.0". The best way for me is to code something like if the user enters for example "1" automatically after pressing the done button, add ".0" to get 1.0?
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let allowedCharacters = "-1234567890."
let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
let typedCharactersSet = CharacterSet(charactersIn: string)
return allowedCharacterSet.isSuperset(of: typedCharactersSet)
}
func TextField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = latDegTextField.text else { return true }
let count = text.count + string.count - range.length
return count == 2
}
First of all use this method from HERE which is
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField.text != "" || string != "" {
let res = (textField.text ?? "") + string
return Double(res) != nil
}
return true
}
And in your done button action add this:
#IBAction func btnDoneTapped(_ sender: Any) {
print(tf.text)
guard let obj = Double(tf.text!) else { return }
print(obj)
}
And when you enter 1 and press done button print(tf.text) will print Optional("1") and print(obj) will print 1.0
Use this code :-
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//Will prevent user from entering space as first character
let enteredCharString = "\(textField.text ?? "")\(string )"
if enteredCharString.trimmingCharacters(in: .whitespaces).count == 0 {
return false
}
switch textField {
case txt_Ammount:
if txt_Ammount.text != "" || string != "" {
let res = (txt_Ammount.text ?? "") + string
return Double(res) != nil
}
default:
true
}
return true
}

stopping the repetition of decimal separator in Swift

I have built a compound interest calculator app. App is running almost and now I want to prevent the repetition of the . in the text field.
I have done following three things, but it is not preventing a user from typing more than 1 decimal separator:
conform the class to UITextFieldDelegate
connected the delegate property of the text fields to the view controller
added following functions for principal, interest, freq, years text fields:
func principal(principal: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let existingTextHasDecimalSeparator = principal.text?.rangeOfString(".")
let replacementTextHasDecimalSeparator = string.rangeOfString(".")
if existingTextHasDecimalSeparator != nil && replacementTextHasDecimalSeparator != nil {
return false
}
else {
return true
}
}
func interest(interest: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let existingTextHasDecimalSeparator = interest.text?.rangeOfString(".")
let replacementTextHasDecimalSeparator = string.rangeOfString(".")
if existingTextHasDecimalSeparator != nil && replacementTextHasDecimalSeparator != nil {
return false
}
else {
return true
}
}
func freq(freq: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let existingTextHasDecimalSeparator = freq.text?.rangeOfString(".")
let replacementTextHasDecimalSeparator = string.rangeOfString(".")
if existingTextHasDecimalSeparator != nil && replacementTextHasDecimalSeparator != nil {
return false
}
else {
return true
}
}
func years(years: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let existingTextHasDecimalSeparator = years.text?.rangeOfString(".")
let replacementTextHasDecimalSeparator = string.rangeOfString(".")
if existingTextHasDecimalSeparator != nil && replacementTextHasDecimalSeparator != nil {
return false
}
else {
return true
}
}
Any help is appreciated!
func principal(principal: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
is not how you conform to the protocol.
You have to match the full signature exactly (names matter):
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
You need to use one and check the textField parameter against the text fields in your VC to see which one changed (if you have different behavior).
Since it looks like the four functions you have above are identical, you could just make sure you always refer to the parameter and not to the specific textfield in your implementation.
This code isn't going to work:
if existingTextHasDecimalSeparator != nil && replacementTextHasDecimalSeparator != nil{}
According to Apple's docs, this method returns an NSRange structure giving the location and length in the receiver of the first occurrence of aString. Returns {NSNotFound, 0} if aString is not found or is empty (#"").
So instead of checking for nil you need to check for a non existent range
if existingTextHasDecimalSeparator != NSNotFound && replacementTextHasDecimalSeparator != NSNotFound{}

Detect which character was backspaced in Swift

I want to detect whenever the user backspaces the # key. The code I'm using is:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let char = string.cStringUsingEncoding(NSUTF8StringEncoding)!
let isBackSpace = strcmp(char, "\\b")
if (isBackSpace == -92) {
print("Backspace was pressed")
}
return true
}
..but it doesn't tell me which key was backspaced. Any way to do this?
Backspace doesn't show up in the replacementString argument. The system implements backspace by specifying a range to delete (which will span a single composed character sequence unless the user has selected a range of text), with a replacement string of "" (the empty string). So to detect a backspace or other delete action:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if string == "" && range.length > 0 {
// Backspace or other deletion
let stringToDelete = (textField.text! as NSString).substringWithRange(range)
if stringToDelete == "#" {
print("bye-bye #")
}
}
return true
}

Detect backspace Event in UITextField

I am searching for solutions on how to capture a backspace event, most Stack Overflow answers are in Objective-C but I need on Swift language.
First I have set delegate for the UITextField and set it to self
self.textField.delegate = self;
Then I know to use shouldChangeCharactersInRange delegate method to detect if a backspace was pressed is all code are in Objective-C. I need in Swift these following method as below is used.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
const char * _char = [string cStringUsingEncoding:NSUTF8StringEncoding];
int isBackSpace = strcmp(_char, "\b");
if (isBackSpace == -8) {
// NSLog(#"Backspace was pressed");
}
return YES;
}
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
}
I prefer subclassing UITextField and overriding deleteBackward() because that is much more reliable than the hack of using shouldChangeCharactersInRange:
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 shouldChangeCharactersInRange hack combined with an invisible character that is placed in the text field has several disadvantages:
with a keyboard attached, one can place the cursor before the invisible character and the backspace isn't detected anymore,
the user can even select that invisible character (using Shift Arrow on a keyboard or even by tapping on the caret) and will be confused about that weird character,
the autocomplete bar offers weird choices as long as there's only this invisible character,
Asian language keyboards that have candidate options based on the text field's text will be confused,
the placeholder isn't shown anymore,
the clear button is displayed even when it shouldn't for clearButtonMode = .whileEditing.
Of course, overriding deleteBackward() is a bit inconvenient due to the need of subclassing. But the better UX makes it worth the effort!
And if subclassing is a no-go, e.g. when using UISearchBar with its embedded UITextField, method swizzling should be fine, too.
Swift 5.3
In some version its changed and now it says:
When the user deletes one or more characters, the replacement string
is empty.
So answer for this:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.isEmpty {
// do something
}
return true
}
If you want to detect that some characters will be deleted
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if range.length > 0 {
// We convert string to NSString instead of NSRange to Range<Int>
// because NSRange and NSString not counts emoji as one character
let replacedCharacters = (string as NSString).substring(with: range)
}
return true
}
If you want detect backspaces even on empty textField
class TextField: UITextField {
var backspaceCalled: (()->())?
override func deleteBackward() {
super.deleteBackward()
backspaceCalled?()
}
}
Old answer
Please don't trash your code. Just put this extension somewhere in your code.
extension String {
var isBackspace: Bool {
let char = self.cString(using: String.Encoding.utf8)!
return strcmp(char, "\\b") == -92
}
}
And then just use it in your functions
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.isBackspace {
// do something
}
return true
}
In Swift 3
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let char = string.cString(using: String.Encoding.utf8)!
let isBackSpace = strcmp(char, "\\b")
if (isBackSpace == -92) {
print("Backspace was pressed")
}
return true
}
:)
Try this
public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if(string == "") {
print("Backspace pressed");
return true;
}
}
Note: You can return "true" if you want to allow backspace. Else you can return "false".
If u need detect backspace even in empty textField (for example in case if u need auto switch back to prev textField on backSpace pressing), u can use combination of proposed methods - add invisible sign and use standard delegate method textField:shouldChangeCharactersInRange:replacementString: like follow
Create invisible sign
private struct Constants {
static let InvisibleSign = "\u{200B}"
}
Set delegate for textField
textField.delegate = self
On event EditingChanged check text and if needed add invisible symbol like follow:
#IBAction func didChangeEditingInTextField(sender: UITextField) {
if var text = sender.text {
if text.characters.count == 1 && text != Constants.InvisibleSign {
text = Constants.InvisibleSign.stringByAppendingString(text)
sender.text = text
}
}
}
Add implementation of delegate method textField:shouldChangeCharactersInRange:replacementString:
extension UIViewController : UITextFieldDelegate {
// MARK: - UITextFieldDelegate
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let char = string.cStringUsingEncoding(NSUTF8StringEncoding)!
let isBackSpace = strcmp(char, "\\b")
if (isBackSpace == -92) {
if var string = textField.text {
string = string.stringByReplacingOccurrencesOfString(Constants.InvisibleSign, withString: "")
if string.characters.count == 1 {
//last visible character, if needed u can skip replacement and detect once even in empty text field
//for example u can switch to prev textField
//do stuff here
}
}
}
return true
}
}
I implemented this feature:
And in the case where the last textFiled is empty, I just want to switch to the previous textFiled. I tried all of the answers above, but no one works fine in my situation. For some reason, if I add more logic than print in isBackSpace == -92 parentheses block this method just stopped work...
As for me the method below more elegant and works like a charm:
Swift
class YourTextField: UITextField {
// MARK: Life cycle
override func awakeFromNib() {
super.awakeFromNib()
}
// MARK: Methods
override func deleteBackward() {
super.deleteBackward()
print("deleteBackward")
}
}
Thanks #LombaX for the answer
Swift 4
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let char = string.cString(using: String.Encoding.utf8)!
let isBackSpace = strcmp(char, "\\b")
if isBackSpace == -92 {
print("Backspace was pressed")
return false
}
}
Swift 4
I find the comparison using strcmp irrelevant. We don't even know how strcmp is operating behind the hoods.In all the other answers when comparing current char and \b results are -8 in objective-C and -92 in Swift. I wrote this answer because the above solutions did not work for me. ( Xcode Version 9.3 (9E145) using Swift 4.1 )
FYI : Every character that you actually type is an array of 1 or more elements in utf8 Encoding. backSpace Character is [0]. You can try this out.
PS : Don't forget to assign the proper delegates to your textFields.
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let char = string.cString(using: String.Encoding.utf8)!
if (char.elementsEqual([0])) {
print("Backspace was pressed")
}
else {
print("WHAT DOES THE FOX SAY ?\n")
print(char)
}
return true
}
Swift 4
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//MARK:- If Delete button click
let char = string.cString(using: String.Encoding.utf8)!
let isBackSpace = strcmp(char, "\\b")
if (isBackSpace == -92) {
print("Backspace was pressed")
return true
}
}
Swift 4: If the user presses the backspace button, string is empty so this approach forces textField to only accept characters from a specified character set (in this case utf8 characters) and backspaces (string.isEmpty case).
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.cString(using: String.Encoding.utf8) != nil {
return true
} else if string.isEmpty {
return true
} else {
return false
}
}
Swift 5: Per the text view delegate documentation, if the replacement text returned by the shouldChangeTextIn method is empty, the user pressed the backspace button. If the range upper bound is greater than the range lower bound (or range count is 1 or more), text should be deleted. If the range upper and lower bounds are the same (or both equal 0), then there is no text to delete (a range of length 0 to be replaced by nothing). I tested, and this will get called even on an empty textfield.
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard text.isEmpty else { return true } // No backspace pressed
if (range.upperBound > range.lowerBound) {
print("Backspace pressed")
} else if (range.upperBound == range.lowerBound) {
print("Backspace pressed but no text to delete")
if (textView.text.isEmpty) || (textView.text == nil) {
print("Text view is empty")
}
}
return true
}
I came here looking for an answer of how to detect deletions. I wanted to know when the UITextView was empty after a user taps delete. As I was testing, I realized I needed to capture whole word deletions and cuts as well. Here's the answer I came up with.
extension SomeViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let deleteTapped = text == ""
let cursorAtBeginning = range.location == 0
let deletedCharactersEqualToTextViewCount = range.length == textView.text.count
let everythingWasDeleted = deleteTapped && cursorAtBeginning && deletedCharactersEqualToTextViewCount
if everythingWasDeleted {
// Handle newly empty view from deletion
} else {
// Handle other situation
}
return true
}
}
Thanks for all the previous helpful answers. I hope this helps someone.

Resources