当我尝试过时如何设置可以使用swift输入到UITextField中的最大字符数?,我看到如果我全部使用10个字符,我也无法删除该字符。
我唯一能做的就是取消该操作(一起删除所有字符)。
有谁知道如何不遮挡键盘(以便我不能添加其他字母/符号/数字,但可以使用退格键)?
对于Swift 5和iOS 12,请尝试以下协议实现textField(_:shouldChangeCharactersIn:replacementString:)方法的实现UITextFieldDelegate:
textField(_:shouldChangeCharactersIn:replacementString:)
UITextFieldDelegate
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>
textField
smartInsertDeleteType
UITextSmartInsertDeleteType.no
下面展示了如何实现完整的示例代码textField(_:shouldChangeCharactersIn:replacementString:)中UIViewController:
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 } }