您在项目中多久会看到这样的代码行?
我想了很多。因为我们经常把这样的代码放在我们的视图的开头,因为我们想要扩展它并设置背景。这些行是我们所有视图的基础。在大项目中,我使用 if 10-20 次。
您可以将其替换为:
甚至这样(因为我们将在实现中设置背景的默认值):
这不是一个大的变化,但它确实使您的代码更具可读性和更清晰。这里是这个视图的完整代码,带有一些扩展以制作可点击的关闭背景:
struct ZStackWithBackground<Content: View>: View {
var color: Color
var alignment: Alignment
let tapAction: (() -> ())?
let content: Content
init(color: Color = .red, alignment: Alignment = .center, action tapAction: (() -> ())? = nil, @ViewBuilder content: () -> Content) {
self.color = color
self.alignment = alignment
self.tapAction = tapAction
self.content = content()
}
var body: some View {
if tapAction != nil {
ZStack(alignment: alignment) {
color.ignoresSafeArea()
.onTapGesture {
tapAction?()
}
content
}
} else {
ZStack(alignment: alignment) {
color.ignoresSafeArea()
content
}
}
}
}