UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: help calling methods

Forums > SwiftUI

I have an app that is working ok, but I'm trying to add some preferences to it so that a SettingsView() can manipulate some of it's settings.

in my main view.swift file, i have a set up like this:

Struct BigView: View {
  @State var aVariable: Int = 1
  //lots of these

  func adjustView(input: anExternalStruct?) {
    // this method works fine when called within the scope of BigView somewhere
    // it changes a handful of the @State variables and BigView behaves as expected
  }

  var body: some View {
  ...
  }

}

My question is how do I call the adjustView(input:) method from outside of the struct? it references a lot of the BigView @State variables, as it needs to, but I can't seem to figure out how to make it a public function that can be seen from somewhere else.

I've started the process of moving most of my @State variables out into a seperate userSettings struct, but that comes with it's own confusing and hard to manage

I've also tried moving the adjustView(input:) method out of the BigView struct, but then I can't get it to manipulate any of the @State variables.

any ideas?

3      

My question is how do I call the adjustView(input:) method from outside of the struct?

You don't.

SwiftUI Views don't hang around. They get created and destroyed as needed as the app's state changes. Unlike UIKit's UIViews, you don't keep references to them that you can then call methods on when you need to.

You should rethink your design. It's hard to say exactly how you should do that since we've seen so little of your code, but generally functionality like that should be extracted to a ViewModel or other kind of ObservableObject that you can reference in a View (with @ObservableObject or @StateObject) or pass around in the Environment.

3      

that's the answer I have been suspecting, but I wasn't sure. I working on a better view model now. thanks.

3      

Hacking with Swift is sponsored by Superwall

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.