Last active
January 19, 2023 20:58
-
-
Save prachigauriar/b27a86d2a43e81351639e2e8e90701c8 to your computer and use it in GitHub Desktop.
Trying (and failing) to use formatters SwiftUI TextFields
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 | |
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) } | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This appears to be fixed in Xcode 11 beta 3.