我有两个UIViewControllers,每当他们进入视图时我都想更新。
在 DashBordViewControlller 中,我添加了此代码:
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate! as AppDelegate
appDelegate.dashboardViewController = self
并在 DetailViewController 中使用此代码:
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate! as AppDelegate
appDelegate.detailViewController = self
在 AppDelegate 中,我添加了以下代码:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var dashboardViewController:DashboardViewController?
var detailViewController:DetailViewController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
return true
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
println("Goodbye world")
}
func applicationWillEnterForeground(application: UIApplication) {
println("Hello again world")
dashboardViewController?.cleanCDandQueryHKLoop()
detailViewController?.rememberWhatSegmentIsPressed()
}
我的问题是只要ViewController进入视图,两者 UIViewControllers都会更新。例如,如果我关闭应用程序(主页),然后重新打开它。
如何在AppDelegate中检查哪个ViewController进入视图并仅更新该视图?任何帮助将非常感谢 - 谢谢!
答案 0 :(得分:1)
您应该在视图控制器的viewWillAppear中添加一个观察者,如下所示:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "willEnterForeground:", name: UIApplicationWillEnterForegroundNotification, object: nil)
}
之后,实现你的功能:
func willEnterForeground(notification: NSNotification!) {
// View Controller is brought to Foreground
}
哦,不要忘记在viewWillDisappear上删除观察者:
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: nil, object: nil)
}