Skip to content

Instantly share code, notes, and snippets.

@katsuyoshi
Last active February 12, 2023 13:39
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/a5a4ad6fc0b7ea65eb7233c642ce7334 to your computer and use it in GitHub Desktop.
Save katsuyoshi/a5a4ad6fc0b7ea65eb7233c642ce7334 to your computer and use it in GitHub Desktop.
TextFieldでoptionalを扱う場合について
struct ModelView: View {
@ObservedObject var model: Model
@State var timeStr: String = ""
@State var isEditing = false
@State var timer = Timer.publish(every: 0.1, on: .current, in: .common).autoconnect()
var body: some View {
HStack {
Text(model.name)
TextField("", text: $timeStr) { editing in
isEditing = editing
}
}
.onAppear() {
stopTimer()
reloadTime()
}
.onChange(of: model) { newValue in
startTimer()
}
.onChange(of: isEditing, perform: { editing in
if editing == false,
let t = Double(timeStr) {
debugPrint("save \(model.name)")
model.time = t
}
})
.onReceive(timer) { timer in
stopTimer()
reloadTime()
}
}
private func reloadTime() {
if let t = model.time {
timeStr = String(t)
} else {
timeStr = ""
}
}
private func startTimer() {
timer = self.timer.upstream.autoconnect()
}
private func stopTimer() {
timer.upstream.connect().cancel()
}
}
struct ContentView: View {
@State var selectedModel: Model? = nil
var body: some View {
VStack {
Button("A") {
selectedModel = models[0]
}
Button("B") {
selectedModel = models[1]
}
if let selectedModel {
ModelView(model: selectedModel)
} else {
EmptyView()
}
Spacer()
}
.frame(width: 100, height: 100)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import Foundation
import SwiftUI
class Model: ObservableObject, Equatable {
init(name: String, time: Double?) {
self.name = name
self.time = time
}
var name: String
var time: Double?
static func == (lhs: Model, rhs: Model) -> Bool {
return lhs.name == rhs.name && lhs.time == rhs.time
}
}
var models: [Model] = [
Model(name: "A", time: 1.0),
Model(name: "B", time: 2.0),
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment