gpt4 book ai didi

swift - 将 View 提取为函数或结构?

转载 作者:行者123 更新时间:2023-12-05 09:04:40 25 4
gpt4 key购买 nike

我刚开始学习 Swift 和 SwiftUI。我有一个带有 View 的结构,其中包含一个 VStack。在 VStack 中,我调用了四个返回 View 的函数。

var body: some View {
VStack {

self.renderLogo()
self.renderUserNameTextField()
self.renderPasswordSecureField()
self.renderLoginButton()

}
}

func renderLoginButton() -> some View {
return Button(action: {print("Button clicked")}){
Text("LOGIN").font(.headline).foregroundColor(.white).padding().frame(width: 220, height: 60).background(Color(red: 0, green: 70/255, blue: 128/255)).cornerRadius(15.0)
}.padding()
}[...]

我刚刚读到,将 View 提取到这样的结构中更为常见:

struct UsernameTextField : View {
@Binding var username: String
var body: some View {
return TextField("Username", text: $username)
.padding()
.background(lightGreyColor)
.cornerRadius(5.0)
.padding(.bottom, 20)
}
}

这是为什么呢?使用结构而不是普通函数有什么优势?

最佳答案

这提出了一个有趣的观点。您不希望通过使用带有大量修饰符的标准控件来制作大型 View ,但您希望通过使用函数返回 View 或自定义 View 进行某种形式的重用。

当我在 SwiftUI 中遇到这些问题时,我会查看正在提取的内容。在您的情况下,控件看起来是标准的,但它们应用了不同的样式。线索就在所有带有render 的函数名中。

在这种情况下,我不会使用函数或自定义 View ,而是编写一个自定义修饰符,将一组通用样式应用于控件。您的代码中的几个示例:

首先,创建ViewModifiers

struct InputTextFieldModifier: ViewModifier {
func body(content: Content) -> some View {
content
.padding()
.background(Color.gray)
.cornerRadius(5.0)
.padding(.bottom, 20)
}
}


struct ButtonTextModifier: ViewModifier {
func body(content: Content) -> some View {
content
.font(.headline)
.foregroundColor(.white)
.padding()
.frame(width: 220, height: 60)
.background(Color(red: 0, green: 70/255, blue: 128/255))
.cornerRadius(15.0)
}
}

这些写起来很简单。您只需将所需的修饰符应用于内容参数。

为了使它们更易于使用,您可以为View编写扩展

extension View {
func inputTextFieldStyle() -> some View {
modifier(InputTextFieldModifier())
}

func buttonTextStyle() -> some View {
modifier(ButtonTextModifier())
}
}

这使得调用站点看起来像这样:

var body: some View {
VStack {

...
TextField(...)
.inputTextFieldStyle()
...
Button(action: {print("Button clicked")}){
Text("LOGIN")
.buttonTextStyle()
}.padding()

}
}

如果你想配置修改器,那也很容易。假设您想指定常用文本字段的背景颜色,您可以重写修饰符以将其作为参数:

struct InputTextFieldModifier: ViewModifier {
let backgroundColor: Color

func body(content: Content) -> some View {
content
.padding()
.background(backgroundColor)
.cornerRadius(5.0)
.padding(.bottom, 20)
}
}

并更新您的便利函数以将其作为参数:

extension View {
func inputTextFieldStyle(backgroundColor: Color) -> some View {
modifier(InputTextFieldModifier(backgroundColor: backgroundColor))
}
}

在调用站点:

TextField("Username", text: $username)
.inputTextFieldStyle(backgroundColor: Color.gray)

自定义修饰符是可重用的。

关于swift - 将 View 提取为函数或结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68390800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com