Skip to content

Instantly share code, notes, and snippets.

@prachigauriar
Last active January 19, 2023 20:58
Show Gist options
  • Save prachigauriar/b27a86d2a43e81351639e2e8e90701c8 to your computer and use it in GitHub Desktop.
Save prachigauriar/b27a86d2a43e81351639e2e8e90701c8 to your computer and use it in GitHub Desktop.
Trying (and failing) to use formatters SwiftUI TextFields
import Foundation
import SwiftUI
struct FormattedTextFieldView : View {
@State private var double = 0.5
@State private var nsNumber: NSNumber = 0.5
static let numberFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimum = 0
formatter.maximum = 10
formatter.isPartialStringValidationEnabled = true
formatter.isLenient = true
return formatter
}()
var body: some View {
Form {
Section(header: Text("Bound to Double")) {
HStack {
Text("Double")
Spacer()
TextField("Double Value", value: $double.asNSNumber(), formatter: type(of: self).numberFormatter)
.multilineTextAlignment(.trailing)
}
Slider(value: $double, from: 0, through: 10)
}
Section(header: Text("Bound to NSNumber")) {
HStack {
Text("NSNumber")
Spacer()
TextField("NSNumber Value", value: $nsNumber, formatter: type(of: self).numberFormatter)
.multilineTextAlignment(.trailing)
}
Slider(value: $nsNumber.asDouble(), from: 0, through: 10)
}
}
}
}
extension Binding where Value == Double {
func asNSNumber() -> Binding<NSNumber> {
return Binding<NSNumber>(getValue: {
NSNumber(value: self.value)
}, setValue: {
self.value = $0.doubleValue
})
}
}
extension Binding where Value == NSNumber {
func asDouble() -> Binding<Double> {
return Binding<Double>(getValue: {
self.value.doubleValue
}, setValue: {
self.value = NSNumber(value: $0) }
)
}
}
@prachigauriar
Copy link
Author

This appears to be fixed in Xcode 11 beta 3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment