我正在开发一个应用程序,其中用户需要能够输入“ 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()
}
但这没用。它不打印任何内容,仍然允许用户退格。
任何想法都值得赞赏!
答案 0 :(得分:2)
您只需实现textView(_:shouldChangeTextIn:replacementText:)
并检查empty
replacementText
。
空的replaceText ==按下了退格键
如果text
为Empty
1,则返回false . Else
,返回true。
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text.isEmpty {
return false
}
return true
}
答案 1 :(得分:0)
使用以下代码:
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
}