Ios 禁用粘贴和数字,现在无法擦除UITextField[Swift]中的字母
我有一个UITextField,我禁用了仅粘贴和写入数字字母的选项,但现在,由于某些原因,我无法擦除它 这是我在viewDidLoad中的代码: 这是“不过帐”功能:Ios 禁用粘贴和数字,现在无法擦除UITextField[Swift]中的字母,ios,swift,xcode,uitextfield,Ios,Swift,Xcode,Uitextfield,我有一个UITextField,我禁用了仅粘贴和写入数字字母的选项,但现在,由于某些原因,我无法擦除它 这是我在viewDidLoad中的代码: 这是“不过帐”功能: override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { if action == #selector(NSObject.paste(_:)) { print("n
override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
if action == #selector(NSObject.paste(_:)) {
print("no paste")
return false
}
return super.canPerformAction(action, withSender: sender)
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if string.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet()) != nil {
return true
}
else {
return false
}
}
这是唯一的字母功能:
override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
if action == #selector(NSObject.paste(_:)) {
print("no paste")
return false
}
return super.canPerformAction(action, withSender: sender)
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if string.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet()) != nil {
return true
}
else {
return false
}
}
当按下backspace键时,将调用textfield委托方法,其中textfields文本字符串中最后一个字符的范围和替换字符串作为空字符串的范围。在这种情况下,您当前返回false,这将阻止删除的发生 您可能想要:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return string.isEmpty || string.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet()) != nil
}
当字符串为空字符串时,您应该从textField:shouldChangeCharactersRange:replacementString:返回true。@dan我不明白。。你能把它编码成答案吗?这是我得到的错误:不候选对象生成预期的上下文结果类型“NSCharacterSet”抱歉,缺少一个。现在修复首先-谢谢你的帮助!第二,它是有效的,但由于某些原因,粘贴选项再次可用,我也无法腾出空间。你知道为什么或者如何修复它吗?