NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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?

1      

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.

1      

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

1      

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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.