3 回答

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

TA貢獻1848條經驗 獲得超10個贊
迅速
簡短的回答
使用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
。這是一個示例項目,顯示何時發生的事件。(這是對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") }}
首次啟動應用程序時,輸出順序為:
view did load view will appear did become active view did appear
按下主頁按鈕然后將應用程序帶回前臺后,輸出順序為:
will enter foreground did become active
因此,如果您最初嘗試使用viewWillAppear
那么UIApplication.willEnterForegroundNotification
可能就是您想要的。
注意
從iOS 9及更高版本開始,您無需刪除觀察者。該文件規定:
如果您的應用面向iOS 9.0及更高版本或macOS 10.11及更高版本,則無需在其
dealloc
方法中取消注冊觀察者。
- 3 回答
- 0 關注
- 2080 瀏覽
添加回答
舉報