gpt4 book ai didi

swiftui - UndoManager 的 canUndo 属性未在 SwiftUI 中更新

转载 作者:行者123 更新时间:2023-12-04 01:32:36 30 4
gpt4 key购买 nike

为什么@Environment UndoManager不更新其 canUndo当它的堆栈中有 Action 时的属性?我有一个 View ,它有一个可以使用取消/重做功能的 child ,但由于某种原因,我无法根据管理器禁用撤消按钮。

struct MyView: View {
@Environment(\.undoManager) var undoManager: UndoManager?

var body: some View {
Button("Undo") { ... }
.disabled(!self.undoManager!.canUndo)
}
}

最佳答案

UndoManager.canUndo不符合 KVO,所以使用一些通知发布者来跟踪状态,如下所示

struct MyView: View {
@Environment(\.undoManager) var undoManager
@State private var canUndo = false

// consider also other similar notifications
private let undoObserver = NotificationCenter.default.publisher(for: .NSUndoManagerDidCloseUndoGroup)

var body: some View {
Button("Undo") { }
.disabled(!canUndo)
.onReceive(undoObserver) { _ in
self.canUndo = self.undoManager!.canUndo
}
}
}

关于swiftui - UndoManager 的 canUndo 属性未在 SwiftUI 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60647857/

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