如何在Swift中注册UndoManager? [英] How do I register UndoManager in Swift?
问题描述
如何在Swift中使用UndoManager
(以前是NSUndoManager
)?
How do I use UndoManager
(previously NSUndoManager
) in Swift?
这是我尝试复制的一个Objective-C示例:
Here's an Objective-C example I've tried to replicate:
[[undoManager prepareWithInvocationTarget:self] myArgumentlessMethod];
但是,Swift似乎没有NSInvocation
,这(似乎)意味着我无法在未实现的undoManager
上调用方法.
Swift, however, seems to not have NSInvocation
, which (seemingly) means I can't call methods on the undoManager
that it doesn't implement.
我已经在Swift中尝试了基于对象的版本,但是它似乎使我的Playground崩溃了:
I've tried the object-based version in Swift, but it seems to crash my Playground:
undoManager.registerUndoWithTarget(self, selector: Selector("myMethod"), object: nil)
尽管它似乎崩溃了,即使我的对象接受了AnyObject?
However it seems to crash, even with my object accepts an argument of type AnyObject?
在Swift中执行此操作的最佳方法是什么?有没有一种方法可以避免通过基于对象的注册发送不必要的对象?
What's the best way to do this in Swift? Is there a way to avoid sending an unnecessary object with the object-based registration?
推荐答案
我在一个Playground中尝试过,并且运行正常:
I tried this in a Playground and it works flawlessly:
class UndoResponder: NSObject {
@objc func myMethod() {
print("Undone")
}
}
var undoResponder = UndoResponder()
var undoManager = UndoManager()
undoManager.registerUndo(withTarget: undoResponder, selector: #selector(UndoResponder.myMethod), object: nil)
undoManager.undo()
这篇关于如何在Swift中注册UndoManager?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!