Skip to content

Instantly share code, notes, and snippets.

@katsuyoshi
Last active February 10, 2023 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save katsuyoshi/d9a0087d59b40cd073a10a61d09aa5bb to your computer and use it in GitHub Desktop.
Save katsuyoshi/d9a0087d59b40cd073a10a61d09aa5bb to your computer and use it in GitHub Desktop.
SwiftUIでUndoManagerを試してみる
import SwiftUI
struct ContentView: View {
@ObservedObject var model = Model()
var body: some View {
VStack {
Toggle("On/Off", isOn: $model.isOn)
Spacer()
Button("Undo") {
model.undoManager.undo()
}
.disabled(!model.undoManager.canUndo)
Button("Redo") {
model.undoManager.redo()
}
.disabled(!model.undoManager.canRedo)
}
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import Foundation
class Model: ObservableObject {
var undoManager = UndoManager()
var isOn: Bool = false{
willSet {
debugPrint("willSet: \(self.isOn) -> \(newValue)")
if self.isOn != newValue {
objectWillChange.send()
let v = self.isOn
debugPrint("regist handler")
undoManager.registerUndo(withTarget: self, handler: {
debugPrint("handle: \($0.isOn) -> \(v)")
$0.isOn = v
})
}
}
didSet {
debugPrint("didSet: \(self.isOn)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment