对以下代码进行了处理:
import SwiftUI
struct HomeScreenCounterView: View {
private let value: Int
private let title: String
private let emptyDescription: String
init(value: Int, title: String, emptyDescription: String) {
self.value = value
self.title = title
self.emptyDescription = emptyDescription
}
var body: some View {
VStack {
Text("Messages")
.font(.fontTextLBold)
Text("No new messages")
.font(.fontTextSRegular)
}
.padding()
.clipShape(RoundedRectangle(cornerRadius: 16))
}
}
#Preview {
HomeScreenCounterView(value: 0,
title: "Messages",
emptyDescription: "No new messages")
.foregroundStyle(Color.red)
.background(Color.blue)
}
我得到以下结果:
notice,两个标签中的文本颜色如何更改为红色。尽管背景正确显示为蓝色,但显然没有剪裁,因为剪辑操作员已较早地应用,不以后。
拥有背景颜色修饰符的最好/最优雅的方式,类似于其他SwiftUI组件的工作方式类似?我正在考虑的解决方案之一,显然是一个有效的解决方案,是添加一个初始化程序参数:
init(value: Int, title: String, emptyDescription: String, backgroundColor: Color) {
然后使用该值在
padding
:
之后设置背景颜色。
.padding()
.background(backgroundColor)
.clipShape(RoundedRectangle(cornerRadius: 16))
但是有更好的方法吗?这是我希望最终结果的样子: 您可以考虑使用themantic Shape样式
注意,您还可以使用一个内置的环境价值,但是请注意,其他swiftui视图也可以使用。 然后,您可以编写自己的with to and to to to to to th这个环境价值。
backgroundStyle
usage:在iOS 17之前,您需要一个
struct MyBackgroundStyle: ShapeStyle {
func resolve(in environment: EnvironmentValues) -> AnyShapeStyle {
environment.myBackground
}
}
extension ShapeStyle where Self == MyBackgroundStyle {
static var myBackground: MyBackgroundStyle { .init() }
}
而不是自定义struct HomeScreenCounterView: View {
private let value: Int
private let title: String
private let emptyDescription: String
init(value: Int, title: String, emptyDescription: String) {
self.value = value
self.title = title
self.emptyDescription = emptyDescription
}
var body: some View {
VStack {
Text("Messages")
Text("No new messages")
}
.padding()
.background(.myBackground)
.clipShape(RoundedRectangle(cornerRadius: 16))
}
}
#Preview {
HomeScreenCounterView(value: 0,
title: "Messages",
emptyDescription: "No new messages")
.foregroundStyle(Color.red)
.myBackground(.blue)
}
。
ViewModifier
然后,您将ShapeStyle
替换为struct MyBackgroundModifier: ViewModifier {
@Environment(\.myBackground) var myBackground
func body(content: Content) -> some View {
content.background(myBackground)
}
}
extension View {
func useMyBackground() -> some View {
modifier(MyBackgroundModifier())
}
}