无法在 Swift 4.2 中撤消、重做和再次撤消



在 swift (4.2( 中,我无法重做然后在初始撤消后撤消。UndoManager.registerUndo(...( 中的选择器在重做和后续撤消期间永远不会调用

我已经在项目和游乐场中尝试过这个,有无穷无尽的变化。

import Cocoa
class UndoResponder: NSObject {
    @objc func printSender(_ sender: Any) {
        print("printSender: ", sender)
    }
}
var undoResponder = UndoResponder()
var undoManager = UndoManager()
undoManager.registerUndo(withTarget: undoResponder, selector:
    #selector(UndoResponder.printSender(_:)), object: "Hi!")
print("about to undo")
undoManager.undo()
print("about to redo")
undoManager.redo()
print("about to undo")
undoManager.undo()
// output:
// about to undo
// printSender:  Hi!
// about to redo
// about to undo

预期产出:

// about to undo 
// printSender:  Hi! 
// about to redo 
// printSender:  Hi! 
// about to undo 
// printSender:  Hi!

正如问题评论中指出的那样,我没有注册重做。所以我用以下内容替换:

import Cocoa
class Undoable {
    var undoManager = UndoManager()
    var object: Any = "None"
    @objc func setObject(_ newObject: Any) {
        let oldObject = object
        object = newObject
        undoManager.registerUndo(withTarget: self, selector:
            #selector(Undoable.setObject(_:)), object: oldObject)
    }
    func undo() {
        undoManager.undo()
        print("after undo: ", object)
    }
    func redo() {
        undoManager.redo()
        print("after redo: ", object)
    }
}
let undoable = Undoable()
print("Initial: ", undoable.object)
undoable.setObject(1)
print("After set: ", undoable.object)
undoable.undo()
undoable.redo()
undoable.undo()

输出:

Initial:  (None)
After set:  1
after undo:  (None)
after redo:  1
after undo:  (None)

相关内容

  • 没有找到相关文章

最新更新