'tutorial theme background color not working
Trying to follow this iOS dev tutorial.
When I get to step 7 it the code does not change the background color as it is supposed to.
Quote "Step 7 Add a Color property named mainColor that creates a color using the enumeration’s rawValue. This property initializes a color from the asset catalog."
Here is the code from the theme file:
import SwiftUI
enum Theme: String {
case bubblegum
case buttercup
case indigo
case lavender
case magenta
case navy
case orange
case oxblood
case periwinkle
case poppy
case purple
case seafoam
case sky
case tan
case teal
case yellow
var accentColor: Color {
switch self {
case .bubblegum, .buttercup, .lavender, .orange, .periwinkle, .poppy, .seafoam, .sky, .tan, .teal, .yellow: return .black
case .indigo, .magenta, .navy, .oxblood, .purple: return .white
}
}
var mainColor: Color {
Color(rawValue) // This line not working
}
}
if I change the code to:
var mainColor: Color {
return .red
}
The background changes to red as I would expect.
Code from View File is:
import SwiftUI
struct CardView: View {
let scrum: DailyScrum
var body: some View {
VStack(alignment: .leading) {
Text(scrum.title)
.font(.headline)
.accessibilityAddTraits(.isHeader)
Spacer()
HStack {
Label("\(scrum.attendees.count)", systemImage: "person.3")
.accessibilityLabel("\(scrum.attendees.count) attendees")
Spacer()
Label("\(scrum.lengthInMinutes)", systemImage: "clock")
.accessibilityLabel("\(scrum.lengthInMinutes) minute meeting")
.labelStyle(.trailingIcon)
}
.font(.caption)
}
.padding()
.foregroundColor(scrum.theme.accentColor)
}
}
struct CardView_Previews: PreviewProvider {
static var scrum = DailyScrum.sampleData[0]
static var previews: some View {
CardView(scrum: scrum)
.background(scrum.theme.mainColor) // Here is were theme is called
.previewLayout(.fixed(width: 400, height: 60))
}
}
Solution 1:[1]
Same question: Apple's SwiftUI tutorial code doesn't display view contents in homemade copy
You should download the project files first, and import the assets folder from StartingProject.
Assets folder location:
Solution 2:[2]
Color(rawValue) (where rawValue is a String) will only work if you have the color with the name rawValue in your assets catalog.
To make it work, you can modify your mainColor like this:
var mainColor: Color {
switch self {
case .purple:
return .purple
case .red:
return .red
// Etc.
}
}
Of course, this won't work with things like .bubblegum, because Color doesn't have such standard colors–you should create them yourself in your assets.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mansi |
| Solution 2 |


