从AppDelegate.swift为一个视图控制器分配一个值
我尝试从AppDelegate.swift分配一个值到一个视图控制器没有成功。
我的控制器名为DestinationsViewController
,它在Main.storyboard中的id是destinationsID
。 DestinationsController
embedded在导航控制器中。 我想改变的对象被命名为“标签”。 这是代码:
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. } }
好的,你可以这样做。 但是,如果您更改故事板的结构,则可能会中断。
首先,在DestinationsViewController中,您需要设置一个variables来保存文本,因为我们在渲染视图之前设置文本。 因此,标签将不存在。 当视图加载时,它将设置标签。
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中,我们设置将在视图加载时设置标签的variables。
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
移动代码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") }