我正在按照 本教程学习 Swift 和 SwiftUI。预览的背景颜色未按预期更改。
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)
}
}
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
]
}
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
}
}
我尝试将
scrum.theme.mainColor
更改为.yellow
或scrum.theme.accentColor
,它有效。我不确定这里出了什么问题。
我的Xcode版本是15,Swift是5.9.2。
您可以这样调试视图:
struct CardView: View {
let scrum: DailyScrum
var body: some View {
Self._printChanges()
return Text("Hello, World!")
.background(scrum.theme.mainColor)
}
}
我在控制台中得到的是:
在主捆绑包的资产目录中找不到名为“黄色”的颜色 (/Users/______/Library/Developer/Xcode/UserData/Previews/Simulator 设备/id/数据/容器/捆绑/应用程序/id/Test.app)
代码似乎没有问题,所以请尝试重新启动 Xcode,或使用 ⌘+⌥+p 重新加载预览。
此外,下面的代码应该产生与 ExpectedPreview 相同的结果。复制这个并继续教程怎么样?
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
}
}
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
]
}
import SwiftUI
enum Theme: String {
case indigo
case magenta
case navy
case oxblood
case purple
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)
}
}