What is in SwiftUI for UITextFieldDelegate and keyBoardType?

Hi

I have a simple UIKit app that lets the user enter temperatures in floating point and converts them to a different unit. So steer the user in the right direction, first I made the UITextField.keyboardType property = decimalPad.

Then I set the UITextField.delegate to a UITextFieldDelegate with the method textfield(:shouldChangeCharactersIn:replacementString)

I want to convert the app to SwiftUI but I haven't found any equivalents for those .

Are there replacements for those?

Replies

You can use the following code as a starter.
Code Block Swift
struct ContentView: View {
@State private var text = ""
var body: some View {
TextField("Enter temperature", text: $text)
.keyboardType(.decimalPad)
.onChange(of: text) { newText in
text = newText.filter { "0123456789.".contains($0) }
}
}
}

You may have to add some code to filter out any extra decimal points.

This example formats the number but not while the user is typing.
Code Block Swift
struct ContentView: View {
@State private var number: Float?
var text: Binding<String> {
Binding<String>(
get: {
number == nil ? "" : String(format: "%g", Float(number!))
},
set: {
if $0.isEmpty {
number = nil
} else {
if let value = NumberFormatter().number(from: $0) {
number = value.floatValue
}
}
}
)
}
var body: some View {
TextField("Enter temperature", text: text)
.keyboardType(.decimalPad)
}
}

Thanks
Code Block
.keyboardType(.decimalPad)

is exactly what I wanted.

But there doesn't seem to be a way to intercept keystrokes the way I am using
Code Block
textField(_:shouldChangeCharactersIn:replacementString:)

I think that provides a better user experience.