Swift - func viewWillAppear

Cri*_* C. 17 viewwillappear ios swift

我有一个标准的SingleViewApplication项目.

ViewController.swift

import UIKit
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        println("viewDidLoad");
    }
}
Run Code Online (Sandbox Code Playgroud)

当我启动应用程序时,将调用viewDidLoad.

我的方案:
- 按Home键(applicationDidEnterBackground)
- 调用应用程序(applicationWillEnterForeground)
并且不调用viewDidLoad.

还有另一个功能要覆盖吗?

iDe*_*Dev 53

如果你想viewWillAppear快速使用这个.

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated) // No need for semicolon
}
Run Code Online (Sandbox Code Playgroud)

  • 旧习难改 (';') :) (7认同)
  • 我很好奇:你能解释为什么我们需要通过`false`吗? (3认同)

Sun*_*kas 6

最佳做法是在ViewController中注册UIApplicationWillEnterForegroundNotification和注册UIApplicationWillEnterBackgroundNotification

public override func viewDidLoad()
{
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationWillEnterForeground:", name: UIApplicationWillEnterForegroundNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationWillEnterBackground:", name: UIApplicationDidEnterBackgroundNotification, object: nil)
}

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

func applicationWillEnterForeground(notification: NSNotification) {
    println("did enter foreground")
}

func applicationWillEnterBackground(notification: NSNotification) {
    println("did enter background")
}
Run Code Online (Sandbox Code Playgroud)


Cri*_* C. 5

基于Noah响应:
在ViewController.swift上添加刷新功能并从AppDelegate.swift> applicationWillEnterForeground调用它

ViewController.swift  

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        println("viewDidLoad");
        refresh();
    }

    func refresh(){
        println("refresh");
    }
}
Run Code Online (Sandbox Code Playgroud)

.

AppDelegate.swift
func applicationWillEnterForeground(application: UIApplication!) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    ViewController().refresh();
}
Run Code Online (Sandbox Code Playgroud)

输出:

viewDidLoad  
refresh  
refresh  
refresh  
refresh  
Run Code Online (Sandbox Code Playgroud)

  • 注意`ViewController().refresh()`创建一个Viewcontroller的新实例.此外,由于这不会存储在任何地方`ARC`会立即解除分配. (2认同)

Noa*_*oon 2

viewDidLoad仅当您的视图控制器\xe2\x80\x99s视图首次加载\xe2\x80\x99s视图时调用\xe2\x80\x94,此后它仍保留在内存中,因此通常在您创建视图控制器的另一个实例之前,它永远不会再次被调用。如果您需要在应用程序进入前台时刷新视图控制器中的内容,您应该创建一个方法来执行此操作并从applicationWillEnterForeground.

\n