选择器 swiftui 标签

问题描述 投票:0回答:1

我有这样的代码。就像代码一样,选择器的内容中有图像和标签。我想当我点击选择器选项时仅显示标签。但问题是图像和标签都会显示在选择器标签上。我该如何解决这个问题?

HStack{
    Picker(selection: $selectedVenueType) {
        ForEach(types, id:\.self){type in
            HStack{
                Text(type)
                    .font(.footnote)
                    .foregroundStyle(.black)
                     Spacer()
                     if type != "Select venue type"{
                         Image(getImage(type: type))
                             .resizable()
                             .aspectRatio(contentMode: .fit)
                             .frame(width: UIScreen.main.bounds.height*0.04, height: UIScreen.main.bounds.height*0.04)
                      }
              }.tag(type)
               .frame(width: UIScreen.main.bounds.width*0.78)
          }
      } label: {
          HStack{
              Text("selectedVenueType")
                  .font(.footnote)
                  .foregroundStyle(.black)
                  .labelStyle(.titleOnly)
          }.frame(width: UIScreen.main.bounds.width*0.78, height: UIScreen.main.bounds.height*0.05)
      }.pickerStyle(MenuPickerStyle())
       .frame(width: UIScreen.main.bounds.width*0.78, height: UIScreen.main.bounds.height*0.05)                  
       .background(Color.white)
       .tint(Color.black)
       .cornerRadius(14) // Adjust the corner radius as needed
       .shadow(color: Color(red: 0.27, green: 0.27, blue: 0.27, opacity: 0.2), radius: 2, x: 0, y: 1)
   }

这是我的选择器的代码。

xcode swiftui picker
1个回答
0
投票

Picker
嵌入
Menu
中。与选择器按钮的标题相比,您对菜单标签有更多的控制权。

这是一个例子:

struct ContentView: View {
    
    @State var selection: PickerOption = options[0]
    
    var body: some View {
        Menu {
            Picker("Options", selection: $selection) {
                ForEach(options, id: \.self) { option in
                    Label(option.title, systemImage: option.systemImage)
                }
            }
        } label: {
            // you can control a lot more things here
            // e.g. make it only show the selected item's title
            // and the "up-down" symbol
            HStack {
                Text(selection.title)
                Image(systemName: "chevron.up.chevron.down")
                    .imageScale(.small)
            }
        }

    }
}

struct PickerOption: Hashable {
    let title: String
    let systemImage: String
}


let options = [
    PickerOption(title: "Option 1", systemImage: "circle"),
    PickerOption(title: "Option 2", systemImage: "rectangle"),
]

输出:

旁注:我不建议使用

UIScreen
的大小来布局您的视图。

© www.soinside.com 2019 - 2024. All rights reserved.