每当用户点击我的应用程序的图标并打开它时,我想调用名为update的函数.我该怎么办?每当应用程序启动时,无论是从后台杀死还是用户按下主页按钮,我都可以覆盖哪种方法.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var button: UIButton!
@IBOutlet weak var labeltwo: UILabel!
var NSDateDefalt = NSUserDefaults.standardUserDefaults()
var date : NSDate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
date = NSUserDefaults.standardUserDefaults().objectForKey("yourKey") as? NSDate
label.text = "\(date)"
update()
}
@IBAction func buttona(sender: AnyObject) {
date = NSDate()
label.text = "\(date)"
NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey:"yourKey")
}
func update(){
let now = NSDate()
let seconds = now.timeIntervalSinceDate(date!)
labeltwo.text = "\(seconds))"
}
}
Run Code Online (Sandbox Code Playgroud)
更新:我在我的App Delegate中实现了
func applicationWillEnterForeground(application: UIApplication) {
ViewController().update()
}
Run Code Online (Sandbox Code Playgroud)
lub*_*lis 12
您需要在AppDelegate中实现您的逻辑
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
// first launch
// this method is called only on first launch when app was closed / killed
return true
}
func applicationWillEnterForeground(application: UIApplication) {
// app will enter in foreground
// this method is called on first launch when app was closed / killed and every time app is reopened or change status from background to foreground (ex. mobile call)
}
func applicationDidBecomeActive(application: UIApplication) {
// app becomes active
// this method is called on first launch when app was closed / killed and every time app is reopened or change status from background to foreground (ex. mobile call)
}
}
Run Code Online (Sandbox Code Playgroud)
更新
正如Paulw11所建议的那样,考虑使用applicationWillEnterForeground而不是applicationDidBecomeActive
在ViewController.swift
以viewDidLoad()
相应的方式写入其中任何一个:
NotificationCenter.default.addObserver(self, selector: #selector(self.update), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.update), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
Run Code Online (Sandbox Code Playgroud)
(编辑:Swift 3的更新)
(编辑:删除了这篇文章中不正确的部分.iOS会自动向任何添加的观察者触发这些通知,无需添加代码以在App Delegate中触发它们)
在你的AppDelegate.swift中,有didFinishLaunchingWithOptions
和applicationWillEnterForeground
.
applicationWillEnterForeground
类似于viewWillAppear
您的viewControllers而不是您的应用程序,而didFinishLaunchingWithOptions
类似于viewDidLoad
您的应用程序.有关更多信息,请查看UIApplicationDelegate
归档时间: |
|
查看次数: |
19223 次 |
最近记录: |