Last active
February 10, 2023 07:57
-
-
Save katsuyoshi/d9a0087d59b40cd073a10a61d09aa5bb to your computer and use it in GitHub Desktop.
SwiftUIでUndoManagerを試してみる
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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