我正在代码中实现撤消/重做功能,但是由于某种原因,我的重做功能无法正常工作,这是我的文本视图代码:
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()
}
然后在viewDidLoad中:
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
答案 0 :(得分:0)
这里的问题:
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()
)