完全禁用 'backspace' 被按下 Swift

Completely disable 'backspace' being pressed Swift

我正在开发一个应用程序,用户需要能够键入 'forwards' 但不能删除任何已经键入的内容(例如返回和编辑)。

有几个答案大致是我想要的:

how to handle backspace in uitextfield - 这是 Swift 的旧版本,我认为我在这之后遇到了很多错误(已弃用、缺少参数等)。尝试此操作时,我正在考虑执行以下操作:

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 
}
}

所以我喜欢这种方法的外观:

want to know ever time while pressing on keyboard back button during textfield editing ios

所以我尝试了:

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
}

并通过

使我的 VC 成为 textView 委托
override func viewDidLoad() {
    self.textViewOutlet.delegate = self

    super.viewDidLoad()
}

但这没有用。它不打印任何内容,但仍允许用户退格。

非常感谢任何想法!

您只需实施 textView(_:shouldChangeTextIn:replacementText:) 并检查 empty replacementText.

空替换文本 == 按下退格键

如果 textEmpty 1return false. Elsereturn true`。

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

使用以下代码:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    let  char = text.cString(using: String.Encoding.utf8)!
    let isBackSpace = strcmp(char, "\b")

    if (isBackSpace == -92) {
        return false
    }
    return true
}