在 Swift UI 中使用 ForEach 的下拉选择器中的彩色选项

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

我有兴趣创建类似于下面屏幕截图中显示的菜单。 Sample

此菜单可通过 Mail.app 的 Rules 设置访问。我有兴趣为左侧的符号着色。我不关心

Other...
按钮和功能。

示例

ContentView.swift

import SwiftUI

struct ContentView: View {

    let availableColours: [String] = ["yellow", "green", "red", "blue"]
    @Binding var selectedOption: Int

    var body: some View {
        VStack {
            Picker("Colour:", selection: $selectedOption) {
                ForEach(0..<availableColours.count) { index in
                    HStack {
                        Image(systemName: "rectangle.fill")
                            .symbolRenderingMode(.monochrome)
                            .foregroundColor(.red)
                        Text(availableColours[index]).tag(availableColours[index])
                    }
                }
            }
            .pickerStyle(.menu)
            .padding()
        }
        .frame(maxWidth: 200)
    }
}

struct BindingViewExamplePreviewContainer: View {
    @State private var defaultChoice = 1

    var body: some View {
        ContentView(selectedOption: $defaultChoice)
    }
}

#Preview {
    BindingViewExamplePreviewContainer()
}

应用程序.swift

import SwiftUI

@main
struct ExperimentsDropDownApp: App {
    @State private var defaultChoice = 1
    var body: some Scene {
        WindowGroup {
            ContentView(selectedOption: $defaultChoice)
        }
    }
}

+Color.swift

import SwiftUI
extension Color {

    init?(wordName: String) {
        switch wordName {
        case "clear":       self = .clear
        case "black":       self = .black
        case "white":       self = .white
        case "gray":        self = .gray
        case "red":         self = .red
        case "green":       self = .green
        case "blue":        self = .blue
        case "orange":      self = .orange
        case "yellow":      self = .yellow
        case "pink":        self = .pink
        case "purple":      self = .purple
        case "primary":     self = .primary
        case "secondary":   self = .secondary
        default:            return nil
        }
    }
}

问题

该符号没有颜色。

resulting menu

arrays swift macos swiftui-foreach swiftui-picker
1个回答
1
投票

SF 符号可以使用

.palette
渲染模式显示彩色。

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