Apple 的 SwiftUI 教程代码在自制副本中不显示视图内容 了解问题解决方案

问题描述

我刚刚开始学习 SwiftUI,遵循 Apple 在 this 链接中构建 iOS 应用程序的教程。我从提供的骨架应用程序开始,然后一步一步地跟随最新的 Xcode。 CardView 没有看到我应该看到的内容,而是只显示一个空白的白色矩形。

Apple 提供了一个完全构建的项目,效果很好。我将我从骨架项目中构建的代码与完成的项目附带的代码进行了比较,它们看起来完全相同。然而,我自制的项目副本根本没有在 CardView 中填写任何详细信息。没有颜色、文本或图标,只有一个空白的白色矩形。除了简单地将代码与固定示例进行比较之外,我完全不知道如何调试它。欢迎任何建议。

这是 CardView.swift 的代码

import SwiftUI

struct CardView: View {
    let scrum: DailyScrum
    var body: some View {
        vstack(alignment: .leading) {
            Text(scrum.title).font(.headline)
            Spacer()
            HStack {
                Label("\(scrum.attendees.count)",systemImage: "person.3")
                    .accessibilityElement(children: .ignore)
                    .accessibilityLabel(Text("Attendees"))
                    .accessibilityValue(Text("\(scrum.attendees.count)"))
                Spacer()
                Label("\(scrum.lengthInMinutes)",systemImage: "clock")
                    .padding(.trailing,20)
                    .accessibilityElement(children: .ignore)
                    .accessibilityLabel(Text("Meeting length"))
                    .accessibilityValue(Text("\(scrum.lengthInMinutes) minutes"))
            }
            .font(.caption)
        }
        .padding()
        .foregroundColor(scrum.color.accessibleFontColor)

    }
}

struct CardView_Previews: PreviewProvider {
    static var scrum = DailyScrum.data[0]
    static var previews: some View {
        CardView(scrum: scrum)
            .background(scrum.color)
            .previewLayout(.fixed(width: 400,height: 60))
    }
}

这是我在 Xcode 预览中的代码中看到的图像:

enter image description here

这是我在 Xcode 预览中从 Apple 已经完成的示例代码中看到的:

enter image description here

将我构建的代码与 Apple 提供的代码进行比较似乎可以突出问题,但出现了零差异。项目中的另外两个视图工作正常。除了这个来源CardView.swift之外,还有其他重要的模块吗?

解决方法

了解问题

  1. scrum.color.accessibleFontColor 应用于卡片的 foregroundColor。所以所有的标签、图片、文字等都会受到影响。

  2. accessibleFontColor 似乎根据父颜色返回 blackwhite(在本例中为 scrum.color

  3. 似乎您传递给预览的 Color("Design") 正在返回 clear 颜色,因为起始项目的资产中没有名称为 Design 的颜色。所以预览显示默认的白色作为卡片背景。但它也使用 white 颜色作为前景。所以你会在结果中看到一张纯白色的卡片。

解决方案

  • 注释掉 .foregroundColor(scrum.color.accessibleFontColor)

  • 或者添加资产颜色并按预期命名。

  • 或者给卡片一个手动背景

  • 或者下载完成的版本,然后将过程反向到您所在的位置。