BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

SOLVED: Question: the format to allow TextField instead of Picker

Forums > 100 Days of SwiftUI

@boat  

Hello

In the WeSplit project,

Paul demonstrated how to use segmented with Pickers. I understand this is smart and easy https://www.hackingwithswift.com/books/ios-swiftui/adding-a-segmented-control-for-tip-percentages

Section {
    Picker("Tip percentage", selection: $tipPercentage) {
        ForEach(tipPercentages, id: \.self) {
            Text($0, format: .percent)
        }
    }
    .pickerStyle(.segmented)
}

However , an array of tip percentages have limited users' options when it comes to tipping.

If I still want to use TextField for tips, is there a value: xxx, format: .xxxxx method for me to input any tip percent or even Int/Double value for tips ?

Thanks

Boat

2      

Check out the TextField docs. There you will find several initializers that do exactly what you are looking for in the Creating a Text Field with a Value section. You can use formats such as .currency, .number, and .percent to achieve the desired outcome.

3      

@boat  

Thank you @roosterboy, reading it now !

Have a nice weekend.

Boat

2      

@boat  

It seems this way it could work:


struct ContentView: View {

    @State  private var numberOfPeople = 1
    @State  private var bill = 0
    @State  private var tipPercent: Double

    var body: some View {
        NavigationView {
        Form{
            Section{

         TextField ("How much tip do you like to leave ?", value:self.$tipPercent, formatter: NumberFormatter())
                Section {
                    Text("\(tipPercent)")
                }
                }}}
               }

 struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()

Except the Preview Section is telling me :

1, 'ContentView' initializer is inaccessible due to 'private' protection level

2, Missing argument for parameter 'tipPercent' in call

2      

As the error message indicates, you need to provide an initial value for tipPercent

2      

@boat  

Thank you @roosterboy. It works now !

Can I say that, by providing tipPercent an initial value, I effectively initialized it ?

Boat..

2      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.