TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Changing the color of a segmented picker...breaks if I use a NavigationView

Forums > SwiftUI

This code works until I add the NavigationView (which I need for an app I am writing)... Basically I want the background of each segment to change to the color indicated. Once I wrap the NavigationView it stops working....any idea why?

import SwiftUI
import UIKit

enum PickerColor: String, Hashable, Identifiable, CustomStringConvertible, CaseIterable {
    case red
    case yellow
    case green
    case blue
    case violet

    var id: String { rawValue }
    var description: String { rawValue.capitalized }

    var color: Color {
        switch self {
            case .red: .red
            case .yellow: .yellow
            case .green: .green
            case .blue: .blue
            case .violet: .purple
        }
    }
}

struct ContentView: View {
    @State private var pickerColor: PickerColor = .red

  var body: some View {
    NavigationView {
      GeometryReader { geo in
        VStack {
          Picker(selection: $pickerColor, content: {
            ForEach(PickerColor.allCases) { color in
              Text(color.description)
                .tag(color)
            }
          }, label: EmptyView.init)
          .pickerStyle(.segmented)
          .tint(pickerColor.color)                                   // <- here
          .onAppear(perform: updatePickerColor)
          .onChange(of: pickerColor, updatePickerColor)

        }//vs
        Spacer()
      } //geo
      .padding()
    }
  }//nav

    func updatePickerColor() {
        let appearance = UISegmentedControl.appearance(for: .current)  // <- here
        appearance.selectedSegmentTintColor = UIColor(pickerColor.color)
    }
}
#Preview {
    ContentView()
}

3      

Hi,

if you use NavigationStack it works, NavigationView will be deprecated.

4      

Wow! you would have thought I would of gotten a deprecation warning...that works great! Thank you!!

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.