ChWebsiteApp/CHDataManagement/Views/Generic/OptionalTextField.swift
2024-11-20 13:53:44 +01:00

29 lines
761 B
Swift

import SwiftUI
// A reusable component to handle optional strings with a TextField
struct OptionalTextField: View {
let titleKey: LocalizedStringKey
// The optional text that will be passed in and out of the component
@Binding var text: String?
init(_ titleKey: LocalizedStringKey, text: Binding<String?>) {
self.titleKey = titleKey
self._text = text
}
var body: some View {
TextField(titleKey, text: Binding(
get: {
// Convert `nil` to an empty string for display
text ?? ""
},
set: { newValue in
// Convert an empty string to `nil`
text = newValue.isEmpty ? nil : newValue
}
))
}
}