如何确定第一次启动UIViewController?

时间:2016-09-13 18:18:35

标签: ios swift

我有一个ViewControllers层次结构,以UINavigationViewController为根 我怎样才能知道某些ViewController是第一次启动还是由于导航堆栈的展开而启动了?

4 个答案:

答案 0 :(得分:19)

假设您想知道在首次显示视图控制器时是否正在调用viewWillAppear:(或viewDidAppear:),或者由于另一个视图控制器已被关闭而显示它是否正在显示,您可以轻松地执行以下操作:

更新的Swift版本:

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

    if isBeingPresented || isMovingToParent {
        // This is the first time this instance of the view controller will appear
    } else {
        // This controller is appearing because another was just dismissed
    }
}

较旧的Swift版本:

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    if isBeingPresented() || isMovingToParentViewController() {
        // This is the first time this instance of the view controller will appear
    } else {
        // This controller is appearing because another was just dismissed
    }
}

答案 1 :(得分:0)

当你在导航堆栈上推送新的viewcontroller时,它首次实例化,当你从堆栈中弹出它时,它会被释放或释放。所以当你推或前进时它是第一次,但是当你回到之前的任何一个视图控制器时,当前的vc已经在内存而不是第一次!!!

答案 2 :(得分:0)

在Objective-C上,它看起来像:

-(void) viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    if ([self isBeingPresented] || [self isMovingToParentViewController]) {
        // This is the first time
    } else {
        // This is the NOT first time
    }
}

答案 3 :(得分:0)

isBeingPresented 和 isMovingToParent 是一个棘手的问题。

我的方法是创建一个计数器并在 viewWillAppear 中增加它。

var viewWillAppearCounter = 0

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

    if viewWillAppearCounter == 0 {
        print("viewWillAppear will be executed for the first time")
    } else {
        print("viewWillAppear was already executed \(viewWillAppearCounter) times")
    }
    viewWillAppearCounter += 1
}