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()
@State var isOn: Bool = false
@State var canUndo = false
@State var canRedo = false
var body: some View {
VStack {
Toggle("On/Off", isOn: $isOn)
Spacer()
Button("Undo") {
model.undo()
}
.disabled(!canUndo)
Button("Redo") {
model.redo()
}
.disabled(!canRedo)
.onAppear() {
isOn = model.isOn
canUndo = model.canUndo
canRedo = model.canRedo
}
.onChange(of: isOn
, perform: { newValue in
model.isOn = isOn
})
.onChange(of: model.isOn, perform: { newValue in
isOn = model.isOn
})
.onChange(of: model.canUndo) { newValue in
canUndo = model.canUndo
}
.onChange(of: model.canRedo) { newValue in
canRedo = model.canRedo
}
}
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import Foundation
class Model: NSObject, ObservableObject {
override init() {
super.init()
}
private var undoManager = UndoManager()
var isOn: Bool = false{
willSet {
debugPrint("willSet: \(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)")
}
}
func undo() {
undoManager.undo()
}
func redo() {
undoManager.redo()
}
var canUndo: Bool {
undoManager.canUndo
}
var canRedo: Bool {
undoManager.canRedo
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment