Skip to content

Instantly share code, notes, and snippets.

@mbrandonw
Last active December 17, 2020 05:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbrandonw/cc5da3d487bcf7c4f21c27019a440d18 to your computer and use it in GitHub Desktop.
Save mbrandonw/cc5da3d487bcf7c4f21c27019a440d18 to your computer and use it in GitHub Desktop.

FB7671513

If you run the code below in a playground you will see that tapping the buttons doesn’t change the UI.

However, if you move the GeometryReader to the outside of ViewModelView it will begin working again.

import SwiftUI
import PlaygroundSupport

class ViewModel: ObservableObject {
  @Published var count = 0
}

struct ViewModelView<Content: View>: View {
  @ObservedObject var viewModel = ViewModel()

  let content: (ViewModel) -> Content

  init(@ViewBuilder content: @escaping (ViewModel) -> Content) {
    self.content = content
  }

  var body: some View {
    // move the geometry reader to here to get it working
    // GeometryReader { proxy in 
    self.content(self.viewModel)
    // }
  }
}

let v = ViewModelView { viewModel in
  GeometryReader { proxy in
    HStack {
      Button("-") { viewModel.count -= 1 }
      Text("\(viewModel.count)")
      Button("+") { viewModel.count += 1 }
    }
  }
}

PlaygroundPage.current.setLiveView(v)

The same happens with ScrollViewReader.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment