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() | |
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() | |
} | |
} |
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: 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