Reputation: 395
So I had something like this code
struct MyComponent: View {
@Binding var isShowing: Bool
var body: some View {
Text("sample")
.offset("")
.offset(y: isShowing ? -100: 0) //values just for example
.animation(.easeInOut, value: isShowing)
}
}
I wanted to add a didShow callback whenever isShowing is being true. The problem I got is this code
@Binding var isShowing: Bool {
didSet {
didShow()
}
}
only fires when isShowing is false.
I was stucked here for days.
Upvotes: 1
Views: 209
Reputation: 395
What worked for me is I made an empty View which performs callback inserted on its onAppear and onDisappear
struct CallbackView: View {
let onAppear: (()->())?
let onDisappear: (()->())?
init(onAppear: (()->())? = nil, onDisappear: (()->())? = nil) {
self.onAppear = onAppear
self.onDisappear = onDisappear
}
var body: some View {
VStack {
Spacer()
}
.frame(width: 0, height: 0)
.onAppear {
self.onAppear?()
}
.onDisappear {
self.onDisappear?()
}
}
then I added it in MyComponent's body like:
if isShowing {
CallbackView(onAppear: {
//.. do something
},
onDisappear: {
//.. do something
})
}
Instead of making a struct, this also works if you just make it into an internal View variable inside a View.
This may not be the best way. But it's the only one that worked for me and I'm very happy that I got out of my problem.
Upvotes: 1