Last active
February 12, 2023 13:39
-
-
Save katsuyoshi/a5a4ad6fc0b7ea65eb7233c642ce7334 to your computer and use it in GitHub Desktop.
TextFieldでoptionalを扱う場合について
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 ModelView: View { | |
@ObservedObject var model: Model | |
@State var isEditing = false | |
var body: some View { | |
HStack { | |
Text(model.name) | |
TextField("", text: $model.timeStr) { editing in | |
isEditing = editing | |
} | |
} | |
.onChange(of: isEditing, perform: { editing in | |
if editing == false { | |
model.save() | |
} | |
}) | |
} | |
} | |
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() | |
} | |
} |
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 | |
import SwiftUI | |
class Model: ObservableObject { | |
init(name: String, time: Double?) { | |
self.name = name | |
self.time = time | |
} | |
var name: String | |
var time: Double? | |
private var _timeStr: String? = nil | |
var timeStr: String { | |
get { | |
if let _timeStr { | |
return _timeStr | |
} else { | |
if let t = time { | |
_timeStr = String(t) | |
} else { | |
_timeStr = "" | |
} | |
} | |
return _timeStr! | |
} | |
set { | |
_timeStr = newValue | |
} | |
} | |
public func save() { | |
if let _timeStr, | |
let n = Double(_timeStr) { | |
time = n | |
debugPrint("save \(name)") | |
} | |
_timeStr = nil | |
} | |
} | |
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