【问题标题】:SwiftUI Custom Picker Label Not RenderingSwiftUI 自定义选取器标签未呈现
【发布时间】:2021-09-29 18:02:01
【问题描述】:

更新到 iOS 15 和 Xcode 13 后,我的应用中的选择器不再显示自定义标签。在 iOS 14 设备上运行应用程序,选择器呈现良好。

这是当前实现的代码 sn-p,截图是它目前在 iOS 15 模拟器中的样子。

    @State var selectedNumber: Int = 0
    
    var body: some View {
        Picker(selection: $selectedNumber, label: customLabel) {
            ForEach(0..<10) {
                Text("\($0)")
            }
        }
    }
    
    var customLabel: some View {
        HStack {
            Image(systemName: "paperplane")
            Text(String(selectedNumber))
            Spacer()
            Text("⌵")
                .offset(y: -4)
        }
        .foregroundColor(.white)
        .font(.title)
        .padding()
        .frame(height: 32)
        .background(Color.blue)
        .cornerRadius(16)
    }

【问题讨论】:

标签: ios swift swiftui


【解决方案1】:

@Adam 提供的答案有效。以下是我为防止其他人偶然发现问题所做的修复。

    @State var selectedNumber: Int = 0
    
    var body: some View {
        Menu {
            Picker(selection: $selectedNumber, label: EmptyView()) {
                ForEach(0..<10) {
                    Text("\($0)")
                }
            }
        } label: {
            customLabel
        }
    }
    
    var customLabel: some View {
        HStack {
            Image(systemName: "paperplane")
            Text(String(selectedNumber))
            Spacer()
            Text("⌵")
                .offset(y: -4)
        }
        .foregroundColor(.white)
        .font(.title)
        .padding()
        .frame(height: 32)
        .background(Color.blue)
        .cornerRadius(16)
    }

【讨论】:

  • 此方法似乎不会将列表自动居中于所选值。长列表超出屏幕是个问题。
【解决方案2】:

您可以使用菜单选项作为标签

Menu("Drop Your Label Here") {
                Picker("Please choose a color", selection: $selectedColor)
                {
                    ForEach(colors, id: \.self) {
                        Text($0)
                    }
                }
                
            }
            //.foregroundColor(Color.init("Red"))
            .foregroundColor(Color.red)
        }.frame(width: 300, height: 60)

【讨论】:

    猜你喜欢
    • 2011-03-08
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    相关资源
    最近更新 更多