gpt4 book ai didi

swiftui - 如何访问 SwiftUI 中的 subview ?

转载 作者:行者123 更新时间:2023-12-04 00:25:50 26 4
gpt4 key购买 nike

我正在开发 SwiftUI,感觉它与 React 非常相似。刚才我正在自定义一个 SwiftUI 的 Button 并且有一个问题,无法动态访问 Button 的 subview 以下代码是我要做的:

struct FullButton : View {
var action: () -> Void
var body: some View {
Button(action: action) {
// render children views here even what is that
children
}
}
}

及用法:

VStack {
FullButton(action: {
print('touched')
}) {
Text("Button")
}
}

请问,我有什么错误的想法吗?


更新

取决于@graycampbell 我尝试如下的回答

struct FullButton<Label> where Label : View {
var action: () -> Void
var label: () -> Label

init(action: @escaping () -> Void, @ViewBuilder label: @escaping () -> Label) {
self.action = action
self.label = label
}

var body: some View {
Button(action: action, label: label)
}
}

所以 FullButton看起来和它本身一样好。但是此时我在使用中还有另一个编译错误。

VStack {
FullButton(action: { print("touched") }) {
Text("Fullbutton")
}
}

错误是Referencing initializer 'init(alignment:spacing:content:)' on 'VStack' requires that 'FullButton<Text>' conform to 'View' .
这意味着 FullButton尚未返回 body现在?
我不知道为什么是因为 FullButton仍在扩展View上课。
请告诉我什么是正确的body该类类型的定义。

最佳答案

如果我正确理解您的问题,这就是您要查找的内容:

struct FullButton<Label>: View where Label: View {
var action: () -> Void
var label: () -> Label

var body: some View {
Button(action: self.action, label: self.label)
}
}

这将允许您传递想要在按钮上显示的任何内容,这意味着您在此处的代码现在可以工作:

FullButton(action: {
print("touched")
}) {
Text("Button")
}

更新

多次查看您的问题后,我意识到您的困惑源于对创建普通 Button 时发生的情况的误解。

在下面的代码中,我创建了一个 Button。该按钮有两个参数 - actionlabel

Button(action: {}, label: {
Text("Button")
})

如果我们查看 Button 的文档,我们会看到它是这样声明的:

struct Button<Label> where Label : View

如果我们再查看初始化器,我们会看到:

init(action: @escaping () -> Void, @ViewBuilder label: () -> Label)

actionlabel 都需要闭包。 action 需要一个返回类型为 Void 的闭包,而 label 需要一个返回类型为 @ViewBuilder 的闭包标签。正如在 Button 的声明中定义的那样,Label 是一个表示 View 的泛型,所以真的,label 是期待的一个返回 View 的闭包。

这不是 Button 独有的。以HStack为例:

struct HStack<Content> where Content : View

init(alignment: VerticalAlignment = .center, spacing: Length? = nil, @ViewBuilder content: () -> Content)

Content 在这里的作用与 LabelButton 中的作用相同。

还有一点需要注意 - 当我们创建这样的按钮时...

Button(action: {}) {
Text("Button")
}

...我们实际上正在做同样的事情:

Button(action: {}, label: {
Text("Button")
})

在 Swift 中,当方法调用中的最后一个参数是闭包时,我们可以省略参数标签并将闭包附加到右括号之外。

在 SwiftUI 中,您不能将内容隐式传递给任何 ViewView 必须在其初始化程序中明确接受 @ViewBuilder 闭包。

因此,您不能将 @ViewBuilder 闭包传递给 FullButton,除非 FullButton 接受 @ViewBuilder 闭包作为其初始化程序中的参数,如我的答案开头所示。

关于swiftui - 如何访问 SwiftUI 中的 subview ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56961821/

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