Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing a function when a view appears - Swift

I'm building an app for iOS using the Swift language. I start with a table view controller as my root view controller, and then I have a secondary view controller in which a variable (passData) is defined. This all works fine, and it passes the data correctly (I think) from the secondary view controller back to the primary view controller. However, when the user returns back to the primary view controller, I need a function to execute which will then add the 'addTitle' value to an array. I know how to add it to the array, but...

I don't know how to initiate the function when the view is returned to. What I mean is, after the user is finished on the secondary view controller AND the variable "passData" is defined, they will then push the back button on the navigation bar. I then need the primary view controller to recognise that it is once again being displayed to the user, and then execute the following code:

tableData += [passData]
tableSubtitle += [passDescription]

I have tried the following:

override func viewDidAppear() {
    tableData += [passData]
    tableSubtitle += [passDescription]
}

But this gives the error as Method does not override any method from its superclass.

Essentially, I just need to know how to start a function when the view displays. How can i achieve this?

like image 564
Mydogmaxieboy Avatar asked Dec 15 '14 08:12

Mydogmaxieboy


People also ask

Which method is called every time when you perform some action on view?

The viewDidAppear() function will get called every time the view appears on the screen.

How do you call a view in Swiftui?

This is the Code: struct testView: View { var body: some View { VStack { Text("TextBox") Text("SecondTextBox") self. testFunction() } } func testFunction() { print("This is a Text.") } }

How do you call a function in Swiftui?

As you can see, you define a function by writing func , then your function name, then open and close parentheses, then a block of code marked by open and close braces. You then call that function by writing its name followed by an open and close parentheses.

How do I return a view in Swiftui?

on the -> View return type.


1 Answers

you need to call super.viewDidAppear(animated) and the method signature takes a Bool so you should say:

override func viewDidAppear(animated: Bool)

ProTip: If you want to override a method you can just start typing the method name you want to overload and Xcode will auto suggest the method name and fill in the override declarative. So on a new line start typing viewDid and you should see the viewDidAppear method in the autocompletion drop down. Pressing enter will complete the method signature for you.

like image 61
Daniel Galasko Avatar answered Oct 20 '22 20:10

Daniel Galasko