重做未在swift中的UndoManager中工作



我正在代码中实现撤消/重做功能,但由于某些原因,我的重做功能无法在文本视图的代码中工作:

func textViewDidBeginEditing(_ textView: UITextView) {
if descBox.textColor == .lightGray {
DescriptionCell.descPlaceholder = descBox.text
let descText = descBox.text
undoManager?.registerUndo(withTarget: self, handler: {
(targetSelf) in
targetSelf.descBox.text = descText
targetSelf.descBox.textColor = .lightGray
})
descBox.text = nil
descBox.textColor = .black
}
}
func textViewDidEndEditing(_ textView: UITextView) {
if descBox.text.isEmpty {
descBox.text = DescriptionCell.descPlaceholder
descBox.textColor = .lightGray
}
let descText = descBox.text
undoManager?.registerUndo(withTarget: self, handler: {
(targetSelf) in
targetSelf.descBox.text = descText
})
}

然后,我的ViewController工具栏上出现了这个:

@objc func Undo() {
undoManager?.undo()
}
@objc func Redo() {
undoManager?.redo()
}

然后在视图中DidLoad:

let undoKeyboard = UIBarButtonItem(image: UIImage(named: "Image-2"), style: .plain, target: self, action: #selector(Undo))
undoKeyboard.tintColor = .lightGray
let redoKeyboard = UIBarButtonItem(image: UIImage(named: "Image-1"), style: .plain, target: self, action: #selector(Redo))
redoKeyboard.tintColor = .green

此处的问题:

func textViewDidEndEditing(_ textView: UITextView) {
if descBox.text.isEmpty {
descBox.text = DescriptionCell.descPlaceholder
descBox.textColor = .lightGray
}
let descText = descBox.text // <== Incorrect; Text has been set
undoManager?.registerUndo(withTarget: self, handler: { (targetSelf) in
// Here it means to reset the text (which already set in textDidEnd), thus meaningless (unless you made changes somewhere else and want to reset to the set text, which I assume is not what you want to achieve here)
targetSelf.descBox.text = descText
})
}

您在这里写的是用一个设置的文本注册撤消管理器(textViewDidEndEditing表示字段已经更改,因此descBox.text已经更新(。

我建议您将其更改为textViewDidBeginEditing(_:),并在那里注册撤消管理器。样品:

func textViewDidBeginEditing(_ textView: UITextView) {
let descText = descBox.text
undoManager?.registerUndo(withTarget: self, handler: { (targetSelf) in
targetSelf.descBox.text = descText
targetSelf.descBox.resignFirstResponder()
})
}

在那里,当你按下undo时,它会设置上一个文本(在任何更改之前(并退出第一响应程序(也称为endEditing()(

相关内容

  • 没有找到相关文章

最新更新