gpt4 book ai didi

ios - 为什么当应用程序从后台返回时不会调用 viewWillAppear?

转载 作者:IT老高 更新时间:2023-10-28 12:13:56 37 4
gpt4 key购买 nike

我正在编写一个应用程序,如果用户在打电话时正在查看应用程序,我需要更改 View 。

我已经实现了以下方法:

- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSLog(@"viewWillAppear:");
_sv.frame = CGRectMake(0.0, 0.0, 320.0, self.view.bounds.size.height);
}

但是当应用返回前台时它不会被调用。

我知道我可以实现:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];

但我不想这样做。我更愿意将我所有的布局信息放在 viewWillAppear: 方法中,让它处理所有可能的场景。

我什至尝试从 applicationWillEnterForeground: 调用 viewWillAppear:,但我似乎无法确定此时哪个是当前 View Controller 。

有人知道处理这个问题的正确方法吗?我确定我缺少一个明显的解决方案。

最佳答案

swift

简答

使用 NotificationCenter 观察者而不是 viewWillAppear

override func viewDidLoad() {
super.viewDidLoad()

// set observer for UIApplication.willEnterForegroundNotification
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

}

// my selector that was defined above
@objc func willEnterForeground() {
// do stuff
}

长答案

要了解应用何时从后台返回,请使用 NotificationCenter 观察者而不是 viewWillAppear。这是一个示例项目,显示了哪些事件何时发生。 (这是对 this Objective-C answer 的改编。)

import UIKit
class ViewController: UIViewController {

// MARK: - Overrides

override func viewDidLoad() {
super.viewDidLoad()
print("view did load")

// add notification observers
NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

}

override func viewWillAppear(_ animated: Bool) {
print("view will appear")
}

override func viewDidAppear(_ animated: Bool) {
print("view did appear")
}

// MARK: - Notification oberserver methods

@objc func didBecomeActive() {
print("did become active")
}

@objc func willEnterForeground() {
print("will enter foreground")
}

}

第一次启动应用时,输出顺序为:

view did load
view will appear
did become active
view did appear

按下home键后,再将app拉回前台,输出顺序为:

will enter foreground
did become active

因此,如果您最初尝试使用 viewWillAppear,那么 UIApplication.willEnterForegroundNotification 可能就是您想要的。

注意

从 iOS 9 及更高版本开始,您无需移除观察者。 documentation状态:

If your app targets iOS 9.0 and later or macOS 10.11 and later, you don't need to unregister an observer in its dealloc method.

关于ios - 为什么当应用程序从后台返回时不会调用 viewWillAppear?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5277940/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com