Search code examples
swiftswiftuipickerwatchos

How do I change the border color of a Picker


I have a Picker in my View and I don't know how to access the border color. This is the code:

Picker("Select a Project", selection: $selectedProjectString){
            ForEach(projects, id: \.self) {
                Text($0).lineLimit(1).frame(height:120)
            }
        }.foregroundColor(Color.white)
        .frame(height: 120)

The Picker looks like this and I want the green border to be white too.

enter image description here

Thanks

Update:

enter image description here


Solution

  • You can achieve this with a custom extension. You can set your border color to any color. (code is below the image)

    Credit to @Tamas

    enter image description here

    Tested view:

    Picker("Select a Project", selection: $pick){
                    ForEach(animal, id: \.self) {
                        Text($0).lineLimit(1).frame(height:120)
                    }
        }
        .focusBorderColor(color: .red)
        .foregroundColor(Color.white)
        .frame(height: 120)
    

    Extension:

    extension Picker {
    func focusBorderColor(color: Color) -> some View {
        let isWatchOS7: Bool = {
            if #available(watchOS 7, *) {
                return true
            }
            return false
        }()
    
        let padding: EdgeInsets = {
            if isWatchOS7 {
                return .init(top: 17, leading: 0, bottom: 0, trailing: 0)
            }
            return .init(top: 8.5, leading: 0.5, bottom: 8.5, trailing: 0.5)
        }()
    
        return self
            .overlay(
                RoundedRectangle(cornerRadius: isWatchOS7 ? 8 : 7)
                    .stroke(color, lineWidth: isWatchOS7 ? 4 : 3.5)
                    .offset(y: isWatchOS7 ? 0 : 8)
                    .padding(padding)
            )
      }
    }