简体   繁体   English

如何快速访问Mac OS应用程序的undoManager?

[英]How do I access the undoManager for my Mac OS app in swift?

I am simply trying to get undo working for the actions a user performs in my app. 我只是想让撤消适用于用户在我的应用中执行的操作。 By default, any text editing the user does has the benefit of undo, but any actions that are done otherwise (from my code) does not. 默认情况下,用户执行的任何文本编辑都具有撤消的优势,但其他方式(根据我的代码)执行的任何操作均不具有撤消的优势。

I can see the documentation explains that I need to get an instance of NSUndoManager and call registerUndoWithTarget, but I am stumped with the first step: getting the undoManager from within my ViewController. 我可以看到文档说明,我需要获取NSUndoManager的实例并调用registerUndoWithTarget,但第一步却很困难:从ViewController中获取undoManager。 Since ViewController is a UIResponder, I tried this: 由于ViewController是UIResponder,因此我尝试了以下操作:

if let undoManager = self.undoManager {
            undoManager.registerUndoWithTarget(self, selector: Selector("removeLatestEntry:"), object: "test")
        }

Since that binding returns nil, I thought maybe the ViewController doesn't have the undoManager, so I looked for it in the window: 由于该绑定返回nil,所以我认为ViewController可能没有undoManager,因此我在窗口中寻找它:

if let window = NSApplication.sharedApplication().mainWindow {
        if let undoManager = window.undoManager {
            undoManager.registerUndoWithTarget(self, selector: Selector("removeLatestEntry:"), object: "test")
        }
    }

Alas, the window binding also returns nil. window,窗口绑定也返回nil。 Sorry, I am very new to this. 抱歉,我对此很陌生。 Can anyone point me in the right direction? 谁能指出我正确的方向? Am I supposed to implement my own undoManager or something? 我应该实现自己的undoManager还是其他东西? There is clearly an undoManager somewhere because anything a user does manually in my textField is getting undo behavior. 显然在某处有一个undoManager,因为用户在我的textField中手动执行的任何操作都会得到撤消行为。 It seems like this would be a singleton that I could access easily from a ViewController. 看来这是我可以从ViewController轻松访问的单例。

-- Edit: BTW, the code above was placed in viewDidLoad and removeLatestEntry is just a function in my ViewController that takes a string and prints it at this point. -编辑:顺便说一句,上面的代码放置在viewDidLoad中,而removeLatestEntry只是我的ViewController中的一个函数,该函数接受一个字符串并在此时打印它。

To use undoManager, the ViewController needs to be first responder. 要使用undoManager,ViewController必须是第一响应者。 So: 所以:

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    becomeFirstResponder()
}

Then, from wherever your action is defined that needs to be reversed, you register your undo and pass it whatever it needs to undo that action. 然后,从定义了需要撤消的操作的任何地方,注册撤消操作并将其传递给撤消该操作所需的任何内容。 So in my case: 因此,就我而言:

func addEntry(activity: String) {
    // some other stuff…
    undoManager!.registerUndoWithTarget(self, selector: Selector("removeLatestEntry:"), object: activity)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM