'SwiftUI Textfield state change stopped working with iOS 15.4.1
The following code has worked fine until iOS 15.4.1. It simply enables a button next to a textfield after the value entered is greater than 100000. It still works with 15.3.1 but stopped working with 15.4.1. Any idea what was changed to prevent it from working?
import SwiftUI
struct ContentView: View {
@State private var woid:Int? = nil
@State var showResults = false
private var woidFormatter:NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.groupingSeparator = ""
return formatter
}()
var body: some View {
Form {
Section(header: Text("Work Order Lookup")) {
HStack {
TextField("Work Order Number", value: $woid, formatter: woidFormatter)
.keyboardType(.numberPad)
Spacer()
Button("Lookup") {
showResults.toggle()
}.buttonStyle(PurpleButton(disabled: (woid ?? 0) < 100000))
.disabled((woid ?? 0) < 100000)
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct PurpleButton: ButtonStyle {
let disabled:Bool
let cardColor:Color = Color(#colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1))
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding()
.background(disabled ? Color.gray : cardColor)
.foregroundColor(.white)
.clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
}
}
Solution 1:[1]
I'm not sure why it worked before but the proper signature for using optionals is this one:
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
public init<F>(_ titleKey: LocalizedStringKey, value: Binding<F.FormatInput?>, format: F, prompt: Text? = nil) where F : ParseableFormatStyle, F.FormatOutput == String
Changing this line:
TextField("Work Order Number", value: $vm.woid, formatter: woidFormatter)
to this works
TextField("Work Order Number", value: $vm.woid, format: .number)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ShouldHaveBeen |