NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

Other/custom text input in picker

Forums > SwiftUI

Hi everyone,

I'm just getting started on my Swift/UI journey, coming over from web/React land. I'm so grateful all the content here and the community.

I just finished the WeSplit app and I have a question about Picker. Let's say we want to give the user an easy way to pick common values for number of people, say 2 to 6. Then give them the ability to manually enter in values greater than 6.

Is there a standard iOS way to do this? I tried adding a TextField at the end of the Picker selections. However I got stuck trying to tie its state back to the Picker's bound state.

Thoughts?

   

Hi shunicorn

While I think I understand what you want to do, however think the Picker is the to restrict to a list of items etc. So you would need to make a custom picker.

A video from Stewart Lynch Reuable Custom PickerView for SwiftUI might help you get in the direction you want.

Nigel

   

You will need to handle the numbers out of the picker range yourself with whatever processing maybe necessary for a maximum, or minimum range of numbers (outside the picker range).

@State var anumber: String = ""

var commonNumbers: [String] = ["2","3","4","5","6"]

var body: some View {
    VStack(alignment: .leading) {
        Text("Tap a number to choose it")
        Picker("Pick a number", selection: $anumber) {
            ForEach(commonNumbers, id: \.self) { aNumber in
                Image(systemName: "\(aNumber).circle.fill")
            }
        }
        .pickerStyle(SegmentedPickerStyle())
    }
    .padding()

    HStack {
        Text("Manual entry")
        TextField("Input number", text: $anumber)
    }
    .padding()

    Text("Chosen number is \(anumber == "" ? "nothing yet" : anumber)")
}

   

Thanks @NigelGee. The custom PickerView looks cool. I'll try that out.

   

@Greenamberred thanks for your ideas as well. I think it might be good to only show the manual text field if the user selects an Other option or something like that. Will play with it!

   

Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!

Get started now

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

Reply to this topic…

You need to create an account or log in to reply.

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.