1

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.

4
  • 2
    The @Binding property wrapper does not call didSet Commented May 27, 2021 at 14:09
  • 1
    stackoverflow.com/a/67364058/505763 should be your solution. Commented May 27, 2021 at 16:18
  • 1
    Does this answer your question? How to observe updates in binded values SwiftUI Commented May 27, 2021 at 16:20
  • @Chen-HaiTeng Yes it works! Only problem with this is it's for ios 14 and above only. But yeah, thanks! Commented May 27, 2021 at 17:33

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.