我有一个UITextField我禁用了粘贴和写入数字的选项(仅限字母),但现在,由于某种原因,我无法删除!
这是viewDidLoad
中的代码:
var textField1 = UITextField()
textField1.frame = CGRectMake(20, 30, view.frame.width - 20, 30)
textField1.backgroundColor = UIColor.clearColor()
textField1.borderStyle = UITextBorderStyle.None
textField1.keyboardType = .Default
textField1.allowsEditingTextAttributes = true
textField1.font = UIFont(name: "MyriadHebrew-Regular", size: 30)
textField1.textColor = UIColor(red: 255/255, green: 215/255, blue: 0, alpha: 1)
textField1.tintColor = UIColor(red: 255/255, green: 215/255, blue: 0, alpha: 1)
textField1.delegate = self
view.addSubview(textField1)
这是非发布功能:
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
}
}
答案 0 :(得分:-1)
当按下退格键时,将调用textfield委托方法,其中textfields文本字符串中的最后一个字符的范围和替换字符串为空字符串。在这种情况下,您当前正在返回false
,以防止发生删除。
你可能想要:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return string.isEmpty || string.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet()) != nil
}