3 回答

TA貢獻(xiàn)1943條經(jīng)驗(yàn) 獲得超7個(gè)贊
該方法viewWillAppear應(yīng)該在您自己的應(yīng)用程序中發(fā)生的事情的上下文中進(jìn)行,而不是在您從另一個(gè)應(yīng)用程序切換回應(yīng)用程序時(shí)將應(yīng)用程序置于前臺的上下文中。
換句話說,如果有人查看另一個(gè)應(yīng)用程序或接聽電話,然后切換回您之前在后臺運(yùn)行的應(yīng)用程序,您的UIViewController在您離開應(yīng)用程序時(shí)已經(jīng)可見“不關(guān)心”可以這么說 - 就它而言,它永遠(yuǎn)不會消失,而且它仍然可見 - 因此viewWillAppear不被稱為。
我建議不要打電話給viewWillAppear自己 - 它有一個(gè)特定的含義,你不應(yīng)該顛覆!您可以通過重構(gòu)來實(shí)現(xiàn)相同的效果,如下所示:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self doMyLayoutStuff:self];
}
- (void)doMyLayoutStuff:(id)sender {
// stuff
}
然后你也doMyLayoutStuff從相應(yīng)的通知中觸發(fā):
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doMyLayoutStuff:) name:UIApplicationDidChangeStatusBarFrameNotification object:self];
順便說一下,沒有開箱即用的方法來判斷哪個(gè)是'當(dāng)前'的UIViewController。但你可以找到解決方法,例如UINavigationController的委托方法,用于找出何時(shí)在其中呈現(xiàn)UIViewController。您可以使用這樣的東西來跟蹤已經(jīng)呈現(xiàn)的最新UIViewController。
更新
如果您在各個(gè)位上使用適當(dāng)?shù)淖詣诱{(diào)整掩碼布局UI,有時(shí)您甚至不需要處理UI中的“手動” - 它只是處理...

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超10個(gè)贊
迅速
簡短的回答
使用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}
答案很長
要了解應(yīng)用程序何時(shí)從后臺返回,請使用NotificationCenter
觀察者而不是viewWillAppear
。這是一個(gè)示例項(xiàng)目,顯示何時(shí)發(fā)生的事件。(這是對Objective-C答案的改編。)
import UIKitclass 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") }}
首次啟動應(yīng)用程序時(shí),輸出順序?yàn)椋?/p>
view did load view will appear did become active view did appear
按下主頁按鈕然后將應(yīng)用程序帶回前臺后,輸出順序?yàn)椋?/p>
will enter foreground did become active
因此,如果您最初嘗試使用viewWillAppear
那么UIApplication.willEnterForegroundNotification
可能就是您想要的。
注意
從iOS 9及更高版本開始,您無需刪除觀察者。該文件規(guī)定:
如果您的應(yīng)用面向iOS 9.0及更高版本或macOS 10.11及更高版本,則無需在其
dealloc
方法中取消注冊觀察者。
- 3 回答
- 0 關(guān)注
- 2079 瀏覽
添加回答
舉報(bào)