How to do some stuff in viewDidAppear only once?

前端 未结 8 1422
暖寄归人
暖寄归人 2020-11-29 03:25

I want to check the pasteboard and show an alert if it contains specific values when the view appears. I can place the code into viewDidLoad to ensure it\'s onl

8条回答
  •  有刺的猬
    2020-11-29 04:05

    There is a standard, built-in method you can use for this.

    Objective-C:

    - (void)viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
    
        if ([self isBeingPresented] || [self isMovingToParentViewController]) {
            // Perform an action that will only be done once
        }
    }
    

    Swift 3:

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    
        if self.isBeingPresented || self.isMovingToParentViewController {
            // Perform an action that will only be done once
        }
    }
    

    The call to isBeingPresented is true when a view controller is first being shown as a result of being shown modally. isMovingToParentViewController is true when a view controller is first being pushed onto the navigation stack. One of the two will be true the first time the view controller appears.

    No need to deal with BOOL ivars or any other trick to track the first call.

提交回复
热议问题