9871

SwiftUI two-way binding to value inside ObservableObject inside enum case

<h3>Question</h3>

I am trying to observe changes of a bool value contained in an ObservableObject which is a value in an enum case. Here is an example of what I am trying to achieve but with the current approach I receive the error Use of unresolved identifier '$type1Value'.

import SwiftUI import Combine class ObservableType1: ObservableObject { @Published var isChecked: Bool = false } enum CustomEnum { case option1(ObservableType1) } struct Parent: View { var myCustomEnum: CustomEnum var body: AnyView { switch myCustomEnum { case .option1(let type1Value): AnyView(Child(isChecked: $type1Value.isChecked)) // <- error here } } } struct Child: View { @Binding var isChecked: Bool var body: AnyView { AnyView( Image(systemName: isChecked ? "checkmark.square" : "square") .onTapGesture { self.isChecked = !self.isChecked }) } }

I am trying to update the value of isChecked from the interface but since I want to have the ObservableObject which contains the property in an enum like CustomEnum not sure how to do it or if it is even possible. I went for an enum because there will be multiple enum options with different ObservableObject values and the Parent will generate different subviews depending on the CustomEnum option. If it makes any relevance the Parent will receive the myCustomEnum value from an Array of CustomEnum values. Is this even possible? If not, what alternatives do I have? Thank you!


<h3>Answer1:</h3>

Well, never say never... I've found interesting solution for this scenario, which even allows to remove AnyView. Tested with Xcode 11.4 / iOS 13.4

Provided full testable module, just in case.

// just for test struct Parent_Previews: PreviewProvider { static var previews: some View { Parent(myCustomEnum: .option1(ObservableType1())) } } // no changes class ObservableType1: ObservableObject { @Published var isChecked: Bool = false } // no changes enum CustomEnum { case option1(ObservableType1) } struct Parent: View { var myCustomEnum: CustomEnum var body: some View { self.processCases() // function to make switch work } private func processCases() -> some View { switch myCustomEnum { case .option1(let type1Value): // main part !! return ObservedHolder(value: type1Value) { object in Child(isChecked: object.isChecked) } } } } // just remove AnyView struct Child: View { @Binding var isChecked: Bool var body: some View { Image(systemName: isChecked ? "checkmark.square" : "square") .onTapGesture { self.isChecked = !self.isChecked } } }

Here is a playmaker

struct ObservedHolder<T: ObservableObject, Content: View>: View { @ObservedObject var value: T var content: (ObservedObject<T>.Wrapper) -> Content var body: some View { content(_value.projectedValue) } }
<h3>Answer2:</h3>

This could work for your case:

import SwiftUI class ObservableType1: ObservableObject { @Published var isChecked: Bool = false } enum CustomEnum { case option1(ObservableType1) } struct Parent: View { var myCustomEnum: CustomEnum var body: AnyView { switch (myCustomEnum) { case .option1: return AnyView(Child()) default: return AnyView(Child()) } } } struct Child: View { @ObservedObject var type1 = ObservableType1() var body: AnyView { AnyView( Image(systemName: self.type1.isChecked ? "checkmark.square" : "square") .onTapGesture { self.type1.isChecked.toggle() }) } }

来源:https://stackoverflow.com/questions/62029382/swiftui-two-way-binding-to-value-inside-observableobject-inside-enum-case

Recommend

  • TabView (SwiftUI): Respond onTab on an already active tabItem
  • c++ const public field vs. a getter method
  • Open StreetMap Reverse Geocoding
  • cobertura-maven-plugin with Java 8
  • Is there a way to sort the firebaserecyclerview after I calculate value after retrieving data?
  • What type of password I have to give to set the custom account for application pool identity
  • Anyone have any luck writing a very fast tiff viewer/editor in Java?
  • How can I prevent Galaxy S3 from stopping my app when turning idle?
  • How do I turn this commonly used javascript code into a plugin?
  • Pagination With woocomerece without plugins
  • Find.Execute with confirmation dialog
  • Inject Javascript code into a web page
  • kube-apiserver high CPU and requests
  • OWL Api, move class from parent A to B
  • Get File Extension of File Dropped Onto Windows Form [closed]
  • Simple Donut Chart with Raphael
  • Two way binding not working in ng-bootstrap radio button in an angular reactive form
  • Get method parameters with specific annotation in aspect in scala using java reflection
  • Multiple custom authentication with spring security
  • Why is this Animatable property being set again?
  • Octave code for gradient descent using vectorization not updating cost function correctly
  • Sprite animation wobbly / jumping in IE11
  • Misplaced CAGradientLayer on iPhone 6s
  • Access to database zend framework
  • jQuery colorbox breaks postbacks in ASP.NET Web Forms
  • Videos won't upload
  • Failed to resolve: firebase-auth-15.0.0 [closed]
  • Smarter Removing Unnecessary WhiteSpace CSV
  • trigger ontouch event programmatically
  • reshape/remould data frame to create normalized bar chart and pie chart
  • read part of h5 dataset python
  • ssh remote server login script
  • calling IO Operations from thread in ruby c extension will cause ruby to hang
  • customize soft keyboard key preview
  • How to use FirstOrDefault inside Include
  • PHP Permalinks.. how to change?
  • Running R's aov() mixed effects model from Python using rpy2
  • ReferenceError: TextEncoder is not defined
  • How to check if object is null in Java?