当我尝试How to you set the maximum number of characters that can be entered into a UITextField using swift?时,我看到如果我全部使用10个字符,我也无法擦除该字符。
我唯一能做的就是取消操作(一起删除所有字符)。
有谁知道如何不遮挡键盘(这样我就不能添加其他字母/符号/数字,但是我可以使用退格键)?
最佳答案
对于Swift 5和iOS 12,请尝试以下 textField(_:shouldChangeCharactersIn:replacementString:)
方法的实现,它是UITextFieldDelegate
协议(protocol)的一部分:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldText = textField.text,
let rangeOfTextToReplace = Range(range, in: textFieldText) else {
return false
}
let substringToReplace = textFieldText[rangeOfTextToReplace]
let count = textFieldText.count - substringToReplace.count + string.count
return count <= 10
}
range
(NSRange
)到rangeOfTextToReplace
(Range<String.Index>
)的转换。请参阅此video tutorial以了解为何此转换很重要。 textField
的 smartInsertDeleteType
值设置为UITextSmartInsertDeleteType.no
。这将防止在执行粘贴操作时可能会插入(多余的)多余空间。 以下完整的示例代码显示了如何在
textField(_:shouldChangeCharactersIn:replacementString:)
中实现UIViewController
:import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var textField: UITextField! // Link this to a UITextField in Storyboard
override func viewDidLoad() {
super.viewDidLoad()
textField.smartInsertDeleteType = UITextSmartInsertDeleteType.no
textField.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldText = textField.text,
let rangeOfTextToReplace = Range(range, in: textFieldText) else {
return false
}
let substringToReplace = textFieldText[rangeOfTextToReplace]
let count = textFieldText.count - substringToReplace.count + string.count
return count <= 10
}
}