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

SOLVED: How to save custom picker values?

Forums > SwiftUI

@Benji  

Let's assume I have an array of hair colors:

var hairColors = ["brown", "black", "blonde"]

I want the user to be able to add to that array from a Picker or better said from a menu containing a Picker and a Button which would push a sheet to add a new color.

I'm trying to wrap my head around the best way to persist that new color (or the whole array), so I don't just want to be able to pick it once but for as long as the user uses the app. Even better, the then expanded array would sync across devices.

Would UserDefaults make sense technically and wouldn't it be too expensive if I had a few more of these pickers in the app? Creating a CoreData Entity on the other hand seems a bit too much to only save an array of haircolors?

Does anyone have any tips?

Many thanks!

2      

If you are going to eventually sync across devices then you will get involved with CloudKit, which means CoreData is the way forward.

Otherwise, if your app will have different settings in separate devices, then UserDefaults or AppStorage is something to consider (which ever makes more sense for your app).

As you are HWS+ subscriber, you are probably going through the UlitmatePortfolio tutorials, or can at least look through some of the more relevant ones that suit your use case.

3      

@Benji  

Thanks @Greenamberred.

Yeah it's one thing to figure a solution but another to see whether there are any backdraws without plenty years of experience. That's why I was worrying about performance.

As you are HWS+ subscriber, you are probably going through the UlitmatePortfolio tutorials, or can at least look through some of the more relevant ones that suit your use case.

I often do just like with other tutorials I went through. Sometimes it's just difficult to find exactly what I'm looking for :-)

2      

Hi @BenjiTerv

Just a couple a things to note

  1. Colors are not codable as of yet so if you use the ColorPicker then you will have to convert them so you can save them (one of Paul's Live stream did this)
  2. If you make the colors in Assert.xcassert file then now they are Strings which you can save. Then save the selected color
  3. You can have "UserDefault" to cloud using NSUbiquitousKeyValueStore but acts the same so no need to do CoreData for one string! (Check out Stewart Lynch video NSUbiquitousKeyValueStore or iCloud Shared UserDefaults)

    struct MyColorPicker: View {
    @Environment(\.dismiss) var dismiss
    @Binding var selectedColor: String
    let colors: [String] = ["jetBlack", "naturalBlack", "darkBrown", "ashBlonde", "mysticTurquoise","purplePassion", "rubyRed"]
    let colorColumns = [
        GridItem(.adaptive(minimum: 44))
    ]
    
    var body: some View {
        LazyVGrid(columns: colorColumns) {
                ForEach(colors, id: \.self) { color in
                    ZStack {
                        Color(color)
                            .aspectRatio(1, contentMode: .fit)
                            .cornerRadius(6)
    
                        if color == selectedColor {
                            Image(systemName: "checkmark.circle")
                                .foregroundColor(.white)
                                .font(.largeTitle)
                        }
                    }
                    .onTapGesture {
                        selectedColor = color
                        dismiss()
                    }
                }
            }
            .padding()
    }
    }

    Then use that

    struct ContentView: View {
    @AppStorage("selectedColor") var selectedColor = "rubyRed"
    @State private var showingPicker = false
    
    var body: some View {
        HStack {
            Text("Hair color")
    
            Spacer()
    
            Circle()
                .fill(Color(selectedColor))
                .frame(width: 20)
                .onTapGesture {
                    showingPicker.toggle()
                }
    
        }
        .padding()
        .sheet(isPresented: $showingPicker) {
            MyColorPicker(selectedColor: $selectedColor)
                .presentationDetents([.medium])
        }
    
    }
    }

    By changing the Color(color) in MyColorPicker to

    Image(color)
      .resizable()
      .frame(width: 44, height: 44)
      .cornerRadius(6)

    and ContentView to

    Image(selectedColor)
      .resizable()
      .frame(width: 30, height: 30)
      .clipShape(RoundedRectangle(cornerRadius: 6))
      .onTapGesture {
          showingPicker.toggle()
      }

    Screen Recording

3      

@Benji  

Thanks @NigelGee. That's helped a lot.

Colors are not codable as of yet so if you use the ColorPicker then you will have to convert them so you can save them (one of Paul's Live stream did this)

Yeah I see colors were a bad example. For prototyping reasons I had only saved colors as strings.

If you make the colors in Assert.xcassert file then now they are Strings which you can save. Then save the selected color

That's exactly how I do it with other things in the app based off Pauls Ultimate Portfolio tutorial. Again, I didn't think this far with the hair color example.

You can have "UserDefault" to cloud using NSUbiquitousKeyValueStore but acts the same so no need to do CoreData for one string! (Check out Stewart Lynch video NSUbiquitousKeyValueStore or iCloud Shared UserDefaults)

This was really helpful. I got to admit, though, that I'll have to rewatch the video for a third or maybe even fourth time to fully get everything. But that's a great starting point!

Thanks again!

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.