ios - 允许使用字符集退格

标签 ios swift uitextfield

我在删除文本字段时遇到问题。所以我有一个只允许字母的人名文本字段。但是当我点击删除或退格键时,它似乎不起作用。这就是我的代码的样子。

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let set = CharacterSet.letter
    return (string.rangeOfCharacter(from: set) != nil)
}

我不确定为什么退格/删除不起作用。

最佳答案

当用户点击退格键时,string 将为空字符串。所以 rangeOfCharacter 将是 nil 因此您的代码返回 false 阻止退格键工作。

试试这个:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return string.isEmpty || string.rangeOfCharacter(from: CharacterSet.letter) != nil
}

关于ios - 允许使用字符集退格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54450455/

相关文章:

ios - 为什么这个 plist 读/写失败?

ios - 将可输入区域定位在 UITextField 中

ios - 将自己分配给 UITextFieldDelegate 在 iOS 8 中有效,但在 iOS 7 中无效

core-data - swift 1.2 覆盖 NSManagedObject 扩展中的prepareForDeletion

ios - 如何使用 xib 文件在单元格中 rtl UITextField?

ios - 在 UITableView 上选择行时委托(delegate)不起作用

objective-c - iOS: [self.fetchedResultsController performFetch:&error];让我的应用程序崩溃

IOS:从字符串中解析日期

ios - QBChatDelegate-chatDidReceiveMessage : getting called but dialogID is NULL

ios - 检测所有应用程序的手势