gpt4 book ai didi

swiftui - 从 SwiftUI 环境中捕获 UndoManager

转载 作者:行者123 更新时间:2023-12-05 04:58:31 27 4
gpt4 key购买 nike

我希望能够从我的文档模型中访问 UndoManager,这样我就可以在模型中注册撤消操作:

// Assume I've extended MyDocument to conform to ReferenceFileDocument elsewhere...
final class MyDocument {
private var undoManager: UndoManager?

@Published var aNumber = 5 {
willSet {
if let undoManager = undoManager {
let currentValue = self.aNumber
undoManager.registerUndo(withTarget: self) { target in
target.aNumber = currentValue
}
}
}
}

func setUndoManager(undoManager: UndoManager?) {
self.undoManager = undoManager
}
}

要注册undoManager,我试过这个:

struct DocumentView: View {
let document : MyDocument
@Environment(\.undoManager) var undoManager

var body: some View {
MyDocumentEditor(document: document)
.onAppear {
document.setUndoManager(undoManager: undoManager)
}
}
}

当运行我的应用程序并加载保存的文档时,这有效。但是当从一个新文档开始时,UndoManager 为 nil。

我试过这样的事情:

@Environment(\.undoManager) var undoManager { 
didSet {
self.document.setUndoManager(undoManager: undoManager)
}
}

我的目标是尽量在模型和 View 中保留尽可能多的逻辑,并尽可能只关注 UI 内容。我希望 ReferenceFileDocument 提供一个属性来访问其关联的 UndoManager,就像 NSDocument 一样。

最佳答案

SwiftUI 使用下面的方法看起来更自然

var body: some View {
TopLevelView(document: document, undoManager: undoManager)
}

struct TopLevelView: View {
@ObservedObject var document : MyDocument
var undoManager: UndoManager?

init(document: MyDocument, undoManager: UndoManager?) {
self.document = document
self.undoManager = undoManager

self.setUndoManager(undoManager: undoManager)
}

// ... other code
}

关于swiftui - 从 SwiftUI 环境中捕获 UndoManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63919607/

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