如何使用.background()设置CardView背景颜色?

问题描述 投票:0回答:4

我正在关注 SwiftUI 教程 https://developer.apple.com/tutorials/app-dev-training/displaying-data-in-a-list

运行项目的示例下载文件,我可以看到 CardView 使用以下代码包含正确的背景颜色:

        CardView(scrum: scrum)
            .background(scrum.theme.mainColor)

它看起来像这样(它有效):

无论出于何种原因,我已将 Apple 示例文件中的 ALL 代码原样复制到我的本地项目中,但我没有获得背景颜色。

我的本地 Xcode 项目如下所示(即使代码完全相同,也没有背景色):

我从概念上理解了简单的代码。有一个 DailyScrum 模型对象,它有一个属性 Theme。 Theme 枚举有一个

mainColor
。这个
mainColor
被传递到 CardView
.background()

所以我不明白这是一个Xcode问题,一个配置文件问题,一个模拟器问题,还是一个Scheme(运行iPhone模拟器)问题。我不知道为什么在两个不同的 Xcode 项目中运行完全相同的 SwiftUI 代码会导致一个有工作预览,另一个没有工作预览。我在这里缺少什么?

ios swift swiftui
4个回答
3
投票

在Apple的可下载示例项目中,有一个Assets文件夹,其中Themes中命名了颜色。需要创建它以便可以找到指定的颜色。


0
投票

你仔细阅读教程了吗?苹果表示所有这些颜色都在起始项目中。


0
投票

对您的问题多一点输入... 使用 .background() 修饰符需要 Assets 文件夹或视图中的内容,并且声明显示它将返回一个视图,这一点很重要。

让我们看一下声明

func background<Background>(
    _ background: Background,
    alignment: Alignment = .center
) -> some View where Background : View

.background 修饰符可以做什么?

您现在可以像以前一样使用图像。这可以是单一颜色,也可以是城市、百吉饼或其他任何东西的图像。 .background 修饰符为我们提供的更酷的东西是您可以插入和使用的视图。

假设您想要在文件夹系统图像后面有一个矩形。

您现在将创建一个结构体,在其中构建您的背景,并将该结构体作为背景传递到您的图像中。我将向您展示苹果的一个示例。

//here you can find your struct what currently shows the Rectangle background
struct DiamondBackground: View {
    var body: some View {
        VStack {
            Rectangle()
                .fill(Color.gray)
                .frame(width: 250, height: 250, alignment: .center)
                .rotationEffect(.degrees(45.0))
        }
    }
}


struct Frontmost: View {
    var body: some View {
        VStack {
            //here is your image - in this case its a simple systemimage (can found in SFSymbols)
            Image(systemName: "folder")
                .font(.system(size: 128, weight: .ultraLight))
                .background(DiamondBackground())
                //here is the .background modifier with your selfmade DiamondBackground struct 
        }
    }
}

这个例子现在看起来像这样:


0
投票

我在较新的 XCode 15.3 中遇到了这个问题

较新的“#Preview”似乎存在问题。我有与起始项目相同的文件,但在我最近创建的项目版本中,它具有新的“#Preview”格式,如下所示:

#Preview {
let scrum = DailyScrum.sampleData[0]
CardView(scrum: scrum)
    .background(scrum.theme.mainColor)
    .previewLayout(.fixed(width: 400, height: 60))
}

我刚刚用“旧”预览格式替换了它:

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

而且它奏效了。我不确定为什么这不适用于新的“#Preview”。

我希望它对使用 XCode 最新版本的人有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.