TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

TextFields with numbers and also how to align them

Forums > SwiftUI

Noob questions for the code below. 1) For an Int property, I have to initialize with 0 (or some Int). Therefore, that default Int will obscure/replace the placeholder text, correct? 2) Have I set the TextField up correctly to bind the Int? 3) If I do have to have the preceding Text view, how can I right-align the TextField?

@State private var bookPages = 0

Form { HStack { Text("Pages in book") // can I avoid this? TextField("Pages in book", value: $bookPages, formatter: NumberFormatter( )) } }

2      

Just do the following -

@State private var bookPages = ""

var body: some View {
        Form {
               Textfield("Pages in book", value: $bookPages)
               }
}

You will obviously have to check that user has entered an Int and that the string can be converted to an Int so that you can use it as an Int but the above is nice and simple.

2      

Following from first answer

If you require the bookPages to be Int then you could do a

guard let pages = Int(bookPages) else { return }

now pages is a Int

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.