swift - 如何在 SwiftUI WidgetKit 占位符中自定义占位符外观?

标签 swift swiftui ios14 widgetkit

根据我的代码设置方式,当我的 Widget 在实际数据进入之前显示为占位符时,它看起来很难看,因为 Circle() 剪辑路径切断了图像占位符。
enter image description here
这是 SwiftUI 代码(第一个 Image View 是有问题的 View ):

var body: some View {
    VStack {
        HStack(alignment: .center, spacing: 14, content: {
            Image(model.profileIcon).resizable()
                .padding(4)
                .frame(width: 44, height: 44)
                .background(Color("LightColor"))
                .clipShape(Circle())
            VStack(alignment: .leading, spacing: 2, content: {
                Text(model.profileName)
                    .font(.system(size: 16))
                    .bold()
                Text("\(model.practiceToday) today")
                    .font(.system(size: 15)).fontWeight(.regular)
                    .foregroundColor(.gray)
                
            })
            Spacer()
        })
        
        Spacer()
        Divider()
        Spacer()
        
        HStack(alignment: .center, spacing: 10, content: {
            ForEach(0..<7) { i in
                SimpleProgressCircle(
                    progress: CGFloat(model.progress[i]),
                    day: model.weekdays[i],
                    today: i == 6)
            }
        })
        .padding(EdgeInsets(top: 0, leading: 2, bottom: 0, trailing: 2))
    }
    .padding(
        EdgeInsets(top: 17, leading: 15, bottom: 20, trailing: 15))
    .background(Color.foreground)
}
以及主 WidgetKit 文件中的占位符函数:
func placeholder(in context: Context) -> WidgetContent {
    return WidgetContent(
        profileID: "",
        profileName: "----",
        profileIcon: "",
        weekdays: ["","","","","","",""],
        progress: [0,0,0,0,0,0,0],
        practiceToday: "--"
    )
}
理想结果:占位符看起来像一个圆圈,没有内部矩形

最佳答案

一种解决方案是声明:

@Environment(\.redactionReasons) private var reasons
然后像这样使用它:
    if reasons.isEmpty { //Your regular view
      Image("fallback").resizable()
        .padding(4)
        .frame(width: 44, height: 44)
        .background(Color.gray)
        .clipShape(Circle())
    } else { //Example of placeholder
      Image("fallback").resizable()
        //.padding(4)
        .frame(width: 44, height: 44)
        .background(Color.gray)
        .clipShape(Circle())
    }
或者这会做
Image("fallback").resizable()
    .padding(reasons.isEmpty ? 4: 0)

关于swift - 如何在 SwiftUI WidgetKit 占位符中自定义占位符外观?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64075624/

相关文章:

ios - 旋转设备后动画点会重新定位

ios - SwiftUI:如何让 ScrollView 包含完整列表长度

swift - 要求 AppTrackingTransparency 许可使用谷歌分析,是强制性的吗?

admob - 展示 Admob 广告是否需要 ATT 通话?

ios - 应用程序 WidgetKit 描述和名称本地化

ios - 打开谷歌地图应用程序以从另一个应用程序进行导航

ios - 拥有一个 Apple Distribution 证书,但未安装其私钥。联系此证书的创建者以获取私钥的副本

可选泛型类型的 Swift 扩展

ios - 使用不同的起点条目快速混合两个音频文件

ios - 从 MySQL 数据库导入 iOS 应用程序中的数据