最近开始使用SwiftUI学习/开发应用程序,构建UI组件似乎相当容易。但是,在SwiftUI中难以创建一个SwiftUI。我的想法是在BaseView中拥有诸如背景、导航等常见的UI控件,并且只需子类其他SwiftUI视图就可以自动拥有基本组件。
发布于 2019-08-29 13:00:07
通常你想有共同的行为或共同的风格。
( 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,这可能是苹果的首选做法。让我们尝试以不同的方式设计上面的示例
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!")
}
}
}通过这种方式,您可以使用BgView,就像使用VStack或List之类的方式一样。
3)有一个共同的样式:创建一个视图修饰符
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/的非常有用的链接
发布于 2021-02-26 14:07:49
我对如何在SwiftUI中创建一个在其他屏幕中常用的有了一些想法。
顺便说一句,Step .1创建ViewModifier
struct BaseScene: ViewModifier {
/// Scene Title
var screenTitle: String
func body(content: Content) -> some View {
VStack {
HStack {
Spacer()
Text(screenTitle)
.font(.title)
.foregroundColor(.white)
Spacer()
}.padding()
.background(Color.blue.opacity(0.8))
content
}
}
}步骤.2在视图中使用ViewModifer
struct BaseSceneView: View {
var body: some View {
VStack {
Spacer()
Text("Home screen")
.font(.title)
Spacer()
}
.modifier(BaseScene(screenTitle: "Screen Title"))
}
}
struct BaseSceneView_Previews: PreviewProvider {
static var previews: some View {
Group {
BaseSceneView()
}
}
}你的产出如下:

https://stackoverflow.com/questions/57686218
复制相似问题