Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Keyboard type of TextField in SwiftUI?

I can't seem to find any information or figure out how to set the keyboard type on a TextField for SwiftUI. It would also be nice to be able to enable the secure text property, to hide passwords etc.

This post shows how to "wrap" a UITextField, but I'd rather not use any UI-controls if I don't have to. How to make TextField become first responder?

Anyone have any ideas how this can be done without wrapping an old school UI control?

like image 993
Aaron Bertsch Avatar asked Jun 09 '19 18:06

Aaron Bertsch


3 Answers

To create a field where you can enter secure text you can use SecureField($password)

https://developer.apple.com/documentation/swiftui/securefield

If you want to set the contentType of an textField to eg. .oneTimeCode you can do it like this. Also works with keyboardType

TextField($code)
    .textContentType(.oneTimeCode)
    .keyboardType(.numberPad)
like image 194
Viktor Gardart Avatar answered Oct 17 '22 07:10

Viktor Gardart


We no longer need to use hacks. Beta 5 has brought a new modifier to set the keyboard type. For example, to use a number pad:

.keyboardType(.numberPad)

There's also autocapitalization() and an EnvironmentValue disableAutocorrection.

like image 21
kontiki Avatar answered Oct 17 '22 07:10

kontiki


To set TextField's keyboard type you need to add modifier .keyboardType().

TextField(placeHolder, text: "your text here")
    .keyboardType(.numberPad)
like image 11
Rohit Makwana Avatar answered Oct 17 '22 09:10

Rohit Makwana