I'm working on an app where the user needs to be able to type 'forwards' but is not able to delete anything (to go back and edit for example) that has already been typed.
There are a few answers that are roughly what I want :
how to handle backspace in uitextfield - this is an old version of Swift i think as I got a lot of errors following this (deprecated, missing arguments etc). When trying this, I was thinking of doing something like the below :
func disableBackspace() {
//do a check to see if the range of characters has reduced
if range of characters in the string reduces (<0?) {
//if it has then don't allow the 'character' to be typed
return false
}
}
So I then liked the look of this method :
want to know ever time while pressing on keyboard back button during textfield editing ios
So I tried :
func textView(_ textView: UITextView, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//meant to detect if character was a backspace
let char = string.cString(using: String.Encoding.utf8)
let isBackSpace: Int = Int(strcmp(char, "\u{8}"))
if isBackSpace == -8 {
print("Backspace was pressed")
}
//meant to return false to not allow the backspace
return false
}
And have made my VC a textView delegate by doing
override func viewDidLoad() {
self.textViewOutlet.delegate = self
super.viewDidLoad()
}
but that didn't work. It doesn't print anything and still allows the user to backspace.
Any ideas much appreciated!
You need to simply implement textView(_:shouldChangeTextIn:replacementText:)
and check for empty
replacementText
.
Empty replacementText == backspace pressed
If the text
is Empty
1return false. Else
return true`.
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text.isEmpty {
return false
}
return true
}