简体   繁体   中英

How to set up a textfield with Picker as input in SwiftUI

I'm implementing an app which needs a very common scenario: take picker's value as input to an Textfield. With a "done" button at top right of the picker screen which could save the value to textfield. I'm using SwiftUI instead of UIKit. I see a bunch of UIKit solutions but none of them uses only SwiftUI. Is there a way to implement this function in pure swiftUI ?

struct AddFoodView: View{
    @State private var name = ""
    @State private var count : String = "1"
    @State private var category : String = "肉类";
    @State var showCategory = false
    @State var showCount = false
    

    var body: some View{
        ZStack{
            NavigationView{
                List{
                    HStack{
                        Text("食品")
                        TextField("请输入材料名", text: $name);
                    }.padding()
                    HStack{
                        Text("数量")
                        TextField("请选择数量",text:$count,onEditingChanged:{(changed) in
                            self.showCount=changed;
                        }){}
                    }.padding()
                    HStack{
                        Text("种类")
                        TextField("请选择种类",text: $category,onEditingChanged:{(changed) in
                            self.showCategory=changed;
                        }){}
                    }.padding()
                }
            }.navigationBarItems(trailing: NavigationLink(destination: FoodView()){
                Text("保存").foregroundColor(Color.blue).font(.system(size: 18,design: .default))
            })
            
            if self.showCount{
                    ZStack{
                        Rectangle().fill(Color.gray)
                            .opacity(0.5)
                        VStack(){
                            Spacer(minLength: 0);
                            HStack{
                                Spacer()
                                Button(action: {
                                    self.showCount=false;
                                }, label: {
                                    Text("Done")
                                }).frame(alignment: .trailing).offset(x:-15,y:15)
                            }
                            Picker(selection: $count,label: EmptyView()) {
                                ForEach(1..<100){ number in
                                    Text("\(number)")
                                }
                            }.labelsHidden()
                        }            .frame(minWidth: 300, idealWidth: 300, maxWidth: 300, minHeight: 250, idealHeight: 100, maxHeight: 250, alignment: .top).fixedSize(horizontal: true, vertical: true)
                        .background(RoundedRectangle(cornerRadius: 27).fill(Color.white.opacity(1)))
                        .overlay(RoundedRectangle(cornerRadius: 27).stroke(Color.black, lineWidth: 1))
                        Spacer()
                }
            }
           if self.showCategory{
                let categoryArr = ["肉类","蔬菜类","饮料类","调味品类"]
                    ZStack{
                        Rectangle().fill(Color.gray)
                            .opacity(0.5)
                        VStack(){
                            Spacer(minLength: 0);
                            HStack{
                                Spacer()
                                Button(action: {
                                    self.showCategory=false;
                                }, label: {
                                    Text("Done")
                                }).frame(alignment: .trailing).offset(x:-15,y:15)
                            }
                                Picker(selection: $category,label: EmptyView()) {
                                    ForEach(0..<categoryArr.count){ number in
                                        Text(categoryArr[number]).tag(categoryArr[number])
                                    }
                                }.labelsHidden()
                        }            .frame(minWidth: 300, idealWidth: 300, maxWidth: 300, minHeight: 250, idealHeight: 100, maxHeight: 250, alignment: .top).fixedSize(horizontal: true, vertical: true)
                        .background(RoundedRectangle(cornerRadius: 27).fill(Color.white.opacity(1)))
                        .overlay(RoundedRectangle(cornerRadius: 27).stroke(Color.black, lineWidth: 1))
                        Spacer()
                    }
            }
        }.animation(.easeInOut)
    }
        

In the above code, basically when the user is trying to tap on the TextField, I will pop up a "floating" picker let me pick the value. However, the value in the textfield wouldn't change in according with the picker.

As far as I understood your code the issue is due to not aligned types for selection (count is-a String ) and items (item is-a Int ) in Picker , so here is a fix (use tag with same type as selection):

Picker(selection: $count,label: EmptyView()) {
    ForEach(1..<100){ number in
        Text("\(number)").tag("\(number)")  // << here !!
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM