UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.