Warm tip: This article is reproduced from stackoverflow.com, please click
ios swift

How to trigger an action in viewDidAppear only the first time a view controller is shown?

发布于 2020-03-27 10:31:21

Essentially I would like to print the following "hello" message only once when the view appears only the first time when the app first loads. The ViewController can be shown again when a tab in a tab controller triggers it, but it should not print the message after the very first time. Going back to the ViewController should not trigger this "hello" to print.

The following is what I have already tired, but it does not seem to work?

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    if self.isBeingPresented || self.isMovingToParent {
        print("hello")
    }
}
Questioner
user11349745
Viewed
221
Sh_Khan 2019-07-03 23:55

The most stable way is

var once = true

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated) 
    if once {
        print("hello")
        once = false
    }
}

As self.isBeingPresented || self.isMovingToParen can give unexpected results according to where you use it