如何在 SwiftUI WidgetKit 占位符中自定义占位符外观?
Posted
技术标签:
【中文标题】如何在 SwiftUI WidgetKit 占位符中自定义占位符外观?【英文标题】:How to customize placeholder looks in SwiftUI WidgetKit placeholder? 【发布时间】:2021-01-12 11:14:50 【问题描述】:按照我的代码设置方式,当我的 Widget 在实际数据进入之前显示为占位符时,它看起来很难看,因为图像占位符被 Circle() 剪辑路径切断。
这是 SwiftUI 代码(第一个 Image 视图是有问题的视图):
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)
以及主小部件文件中的占位符功能:
func placeholder(in context: Context) -> WidgetContent
return WidgetContent(
profileID: "",
profileName: "----",
profileIcon: "",
weekdays: ["","","","","","",""],
progress: [0,0,0,0,0,0,0],
practiceToday: "--"
)
理想结果:占位符看起来像一个圆圈,没有内部矩形
【问题讨论】:
你解决了吗?你玩过.redacted(reason: .placeholder)
和.unredacted()
properties 吗?
【参考方案1】:
一种解决方案是声明:
@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)
【讨论】:
以上是关于如何在 SwiftUI WidgetKit 占位符中自定义占位符外观?的主要内容,如果未能解决你的问题,请参考以下文章
在 SwiftUI 中向 TextField/SecureField 添加图像,向占位符文本添加填充
从主应用程序目标 SwiftUI 访问 WidgetKit IntentTimelineProvider
isPlaceholder 修饰符不可用且在小部件工具包 + SwiftUI 中不起作用