admin管理员组文章数量:1356442
I want to pass a nullable binding to the view.
public struct Accordion<Trigger, Content>: View where Trigger: View, Content: View {
let trigger: Trigger
let content: Content
@State private var isExpanded = false
// TODO: PASS isExpanded AS A OPTIONAL BINDING FROM OUTSIDE
public init(@ViewBuilder trigger: () -> Trigger, @ViewBuilder content: () -> Content) {
self.trigger = trigger()
self.content = content()
}
public var body: some View {
ZStack {
VStack(spacing: 0.0) {
triggerWrappedView
.onTapGesture {
isExpanded.toggle()
}
content
}
}
}
}
In the view initalizer if we passed a binding use that else somehow create your own binding.
I want to pass a nullable binding to the view.
public struct Accordion<Trigger, Content>: View where Trigger: View, Content: View {
let trigger: Trigger
let content: Content
@State private var isExpanded = false
// TODO: PASS isExpanded AS A OPTIONAL BINDING FROM OUTSIDE
public init(@ViewBuilder trigger: () -> Trigger, @ViewBuilder content: () -> Content) {
self.trigger = trigger()
self.content = content()
}
public var body: some View {
ZStack {
VStack(spacing: 0.0) {
triggerWrappedView
.onTapGesture {
isExpanded.toggle()
}
content
}
}
}
}
In the view initalizer if we passed a binding use that else somehow create your own binding.
Share Improve this question asked Mar 29 at 16:46 Kunal KambleKunal Kamble 1381 silver badge6 bronze badges 3 |1 Answer
Reset to default 2If Accordion
only needs to write (toggle
) to the binding, you can just replace the isExpanded
state with:
let isExpanded: Binding<Bool>?
Initialise it in the initialiser:
public init(isExpanded: Binding<Bool>? = nil, @ViewBuilder trigger: () -> Trigger, @ViewBuilder content: () -> Content) {
self.isExpanded = isExpanded
self.trigger = trigger()
self.content = content()
}
Then use optional chaining when toggling it:
.onTapGesture {
isExpanded?.wrappedValue.toggle()
}
Note that isExpanded
is not a property wrapped in @Binding
. It is of type Binding<Bool>?
, so you need to access wrappedValue
to access the binding's value.
If Accordion
needs to keep track of the isExpanded
state even if the caller did not pass in a binding to its initialiser, you should keep the @State
, in addition to the extra Binding<Bool>?
property. See this post for more info.
本文标签: swiftHow to support optional binding in a viewStack Overflow
版权声明:本文标题:swift - How to support optional binding in a view? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744011491a2575645.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
var selection: Binding<Int>? = nil
– Andrei G. Commented Mar 30 at 0:47isExpanded
in view body, then better just add handler ofonTapGesture
– Cy-4AH Commented Mar 31 at 9:28