gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 13:45:53 24 4
gpt4 key购买 nike

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

我已经在项目和 playground 中尝试过,变化无穷。

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)

关于swift - 无法在 Swift 4.2 中撤消、重做和再次撤消,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55387113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com