SwiftUI | Picker - Change selected row color

拟墨画扇 提交于 2021-02-10 14:32:55

问题


I want to change the color of the selected row.

As you may see, by default it has this light gray color.

I have no idea how to do that since I have found no way to access this row at all. Is there any way to do that?

Demo code:

struct ContentView: View {
    
    var data = Array(0...20).map { "\($0)" }
    @State private var selected = 0

    
    var body: some View {
        VStack {
            Picker("", selection: $selected) {
                ForEach(0 ..< data.count) {
                    Text(data[$0])
                }
            }
        }
    }
}

A UIKit answer would also be welcomed since I have found no way either.

Thank you!


回答1:


Here would be a way to somewhat customize it. The workaround is to just simply put a RoundedRectangle with the color of your choice perfectly underneath it.

It's not perfect, since the gray default opacity overlay is on top of that color and one has to figure out the constraints based on the frame.

struct ContentView: View {
    
    var data = Array(0...20).map { "\($0)" }
    @State private var selected = 0

    
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 5)
                .frame(width: UIScreen.main.bounds.size.width-18, height: 32)
                .foregroundColor(.green)
            
            Picker("", selection: $selected) {
                ForEach(0 ..< data.count) {
                    Text(data[$0])
                }
            }
        }
    }
}


来源:https://stackoverflow.com/questions/64523972/swiftui-picker-change-selected-row-color

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!