从AppDelegate.swift为视图控制器分配值

时间:2014-10-30 12:57:28

标签: ios swift properties appdelegate

我尝试从 AppDelegate.swift 为视图控制器指定一个值,但没有成功。

我的控制器名为DestinationsViewController,其 Main.storyboard 中的ID为destinationsIDDestinationsController嵌入在导航控制器中。我想要更改的对象名为" label"。这是代码:

if let destinationsViewController = storyBoard.instantiateViewControllerWithIdentifier("destinationsID") as? DestinationsViewController {
       if let label = destinationsViewController.label{
            label.text = "Super!"
        }
        else{
            println("Not good 2")
        }
    }
    else {
        println("Not good 1")
    }

不幸的是,我收到了消息:"不好2"。这不好: - (

谢谢。

import UIKit

class DestinationsViewController: UIViewController {

@IBOutlet weak var label: UILabel!

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

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }
}

1 个答案:

答案 0 :(得分:3)

好的,这是你怎么做的。但是,如果您更改故事板的结构,则可能会中断。

首先,在DestinationsViewController中,您需要设置一个保存文本的变量,因为我们在呈现视图之前设置文本。因此,标签尚不存在。加载视图时,它会设置标签。

class DestinationsViewController: UIViewController {

@IBOutlet weak var label: UILabel!
var labelText = String()

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    label.text = labelText
}

现在,在AppDelegate中,我们设置了在视图加载时设置标签的变量。

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    // assuming inital view is tabbar
    let tabBarController = self.window?.rootViewController as UITabBarController
    let tabBarRootViewControllers: Array = tabBarController.viewControllers!

    // assuming first tab bar view is the NavigationController with the DestinationsViewController
    let navView = tabBarRootViewControllers[0] as UINavigationController 
    let destinationsViewController = navView.viewControllers[0] as DestinationsViewController
    destinationsViewController.labelText = "Super!"

    return true
}

修改

重新阅读上一条评论后,我意识到你想在应用程序运行后的某个时刻设置标签。您只需将func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool中的代码移动到您需要的位置即可。然后你也可以直接设置标签,因为视图已被加载。

// assuming inital view is tabbar
let tabBarController = self.window?.rootViewController as UITabBarController
let tabBarRootViewControllers: Array = tabBarController.viewControllers!

// assuming first tab bar view is the NavigationController with the DestinationsViewController
let navView = tabBarRootViewControllers[0] as UINavigationController 
let destinationsViewController = navView.viewControllers[0] as DestinationsViewController

if let label = destinationsViewController.label{
    label.text = "Super DUper!"
}
else{
    println("Not good 2")
}