UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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?

3      

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

3      

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)")
}

3      

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

3      

@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!

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.