最近开始使用 SwiftUI 学习/开发应用程序,构建 UI 组件似乎非常容易。但是,在 SwiftUI 中努力创建 BaseView。我的想法是在 BaseView 中拥有常见的 UI 控件,如 background 、 navigation 等,并将其他 SwiftUI View 子类化以自动拥有基本组件。
最佳答案
通常您希望拥有共同的行为或共同的风格。
1) 有共同的行为:用泛型组合
假设我们需要创建一个 BgView
,它是一个以全屏图像作为背景的 View
。我们想在需要时重用 BgView
。您可以这样设计这种情况:
struct BgView<Content>: View where Content: View {
private let bgImage = Image.init(systemName: "m.circle.fill")
let content: Content
var body : some View {
ZStack {
bgImage
.resizable()
.opacity(0.2)
content
}
}
}
您可以在任何需要的地方使用 BgView
,并且可以将所有您想要的内容传递给它。
//1
struct ContentView: View {
var body: some View {
BgView(content: Text("Hello!"))
}
}
//2
struct ContentView: View {
var body: some View {
BgView(content:
VStack {
Text("Hello!")
Button(action: {
print("Clicked")
}) {
Text("Click me")
}
}
)
}
}
2) 有一个共同的行为:与@ViewBuilder 闭包组合
考虑到所有 SwiftUI API,这可能是 Apple 首选的处理方式。让我们尝试以这种不同的方式设计上面的示例
struct BgView<Content>: View where Content: View {
private let bgImage = Image.init(systemName: "m.circle.fill")
private let content: Content
public init(@ViewBuilder content: () -> Content) {
self.content = content()
}
var body : some View {
ZStack {
bgImage
.resizable()
.opacity(0.2)
content
}
}
}
struct ContentView: View {
var body: some View {
BgView {
Text("Hello!")
}
}
}
这样您就可以像使用 VStack
或 List
或其他任何东西一样使用 BgView
。
3)要有共同的风格:创建一个 View 修饰符
struct MyButtonStyle: ViewModifier {
func body(content: Content) -> some View {
content
.padding()
.background(Color.red)
.foregroundColor(Color.white)
.font(.largeTitle)
.cornerRadius(10)
.shadow(radius: 3)
}
}
struct ContentView: View {
var body: some View {
VStack(spacing: 20) {
Button(action: {
print("Button1 clicked")
}) {
Text("Button 1")
}
.modifier(MyButtonStyle())
Button(action: {
print("Button2 clicked")
}) {
Text("Button 2")
}
.modifier(MyButtonStyle())
Button(action: {
print("Button3 clicked")
}) {
Text("Button 3")
}
.modifier(MyButtonStyle())
}
}
}
这些只是示例,但通常您会发现自己使用上述设计风格之一来做事。
编辑: 关于@functionBuilder(因此关于@ViewBuilder)的一个非常有用的链接https://blog.vihan.org/swift-function-builders/
关于swift - 在 SwiftUI 中创建 BaseView 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57686218/