Swift:禁用或清除 TextField 的撤消

Swift: Disable or Clear Undo for a TextField

当为 TextField 选择 NumberPad 时,iPad 显示全键盘,因此我创建了一个函数来简单地删除所有非数字字符。但是,如果按下非数字键,然后用户按下键盘上的撤消,应用程序会崩溃。

如何禁用 TextField 的撤消功能或至少清除撤消堆栈?

在您的控制器中添加 UITextFieldDelegate。 在您的 viewDidLoad() 中分配 yourTextField.delegate = self。比实现这个方法

public func textFieldShouldClear(textField: UITextField) -> Bool{
    return false // This will disable clear button
}

另外,为了替换文本,我建议使用

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{//Your Logic Here
  }

最后答案很简单,我使用了undoManager removeAllActions,而不是只需要:

undoManager?.removeAllActions()

作为一行,我需要:

myTextField.undoManager?.removeAllActions()

我将它放在 TextField 的 DidChange 操作中。