ios – Unable to change background color of the preview from data of custom struct in SwiftUI


I’m learning Swift and SwiftUI following to this tutorial. The background color of the preview not changed as expected.

The Theme.swift:

import SwiftUI

enum Theme: String {
    // ...others
    case yellow

    var accentColor: Color {
        switch self {
        case /* ...others */ .yellow: return .black // <-- Declare the yellow key for accent color
        case .indigo, .magenta, .navy, .oxblood, .purple: return .white
        }
    }
    var mainColor: Color {
        Color(rawValue)
    }
}

The DailyScrum.swift:

import Foundation

struct DailyScrum {
    var title: String
    var attendees: [String]
    var lengthInMinutes: Int
    var theme: Theme
}

extension DailyScrum {
    static let sampleData: [DailyScrum] =
    [
        DailyScrum(title: "Design",
                   attendees: ["Cathy", "Daisy", "Simon", "Jonathan"],
                   lengthInMinutes: 10,
                   theme: .yellow), // <-- assign yellow to the first item's theme which referred to the `Theme.swift`
        // others
    ]
}

The CardView.swift:

import SwiftUI


struct CardView: View {
    let scrum: DailyScrum
    var body: some View {
        Text("Hello, World!")
    }
}


struct CardView_Previews: PreviewProvider {
    static var scrum = DailyScrum.sampleData[0] // <-- get first item
    static var previews: some View {
        CardView(scrum: scrum)
            .background(scrum.theme.mainColor) // <-- get the mainColor of the first item
    }
}

And what I received in the preview:
preview of the CardView, the background yellow is supposed to appear, but it not.

Expected Preview

I’ve tried to change the scrum.theme.mainColor to .yellow or scrum.theme.accentColor, it works. I’m not sure what’s the problem here.

My Xcode version is 15, and Swift is 5.9.2.

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img