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

how to pass random color in a NavigationLink from a NavigationStack List???

Forums > SwiftUI

New to SwiftUI.

Been playing with making a simple app that renders a list of random colors. When you press the color of choice it loads a full screen render of the selected color with the HEX, RGB and CYMK. I've google together some code but i'm stuck in how to pass the data over and provid the desired HEX, RGB and CYML information in the resulting page.

import SwiftUI import UIKit

public extension Color { static func random(randomOpacity: Bool = false) -> Color { Color ( red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1), opacity: randomOpacity ? .random(in: 0...1) : 1 ) } }

struct ContentView: View { var body: some View { NavigationStack { List { ForEach(0..<51, id: .self) { name in NavigationLink(destination: Text("Text")) { Text("(name)") .foregroundColor(.white)

                }
                    .listRowBackground(Color.random())
                    .navigationTitle("Colors")

            }
        }
        .frame(width: 435)
    }
}

}

Preview {

    ContentView()
}

2      

Hi @netwonder01!

As one of the options you can do as follows:

import SwiftUI

struct ContentView: View {
    // Create array of sample data
    let colorArray: [Color] = {
        var colors = [Color]()
        for _ in 0..<51 {
            let newColor = Color.random()
            colors.append(newColor)
        }
        return colors
    }()

    var body: some View {
        NavigationStack {
            List(colorArray, id: \.self) { color in
                NavigationLink(value: color) {
                    Text(color.description)
                        .foregroundStyle(.white)
                }
                .listRowBackground(color)
            }
            .navigationTitle("Colors")
            .navigationDestination(for: Color.self) { color in
                DetailView(color: color)
            }
        }
    }
}

struct DetailView: View {
    let color: Color

    var body: some View {
        Color(color)
            .ignoresSafeArea()
    }
}

public extension Color {
    static func random(randomOpacity: Bool = false) -> Color {
        Color(red: .random(in: 0...1),
              green: .random(in: 0...1),
              blue: .random(in: 0...1),
              opacity: randomOpacity ? .random(in: 0...1) : 1)
    }
}

2      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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.