使用带有 Swift 的 Xcode 6.0.1 我在 Storyboard中创建了一个标签并将其连接到 ViewController.swift 导致:
@IBOutlet weak var myLabel: UILabel!
每当我的应用程序进入前台时,我想将 myLabel.text 重置为某个字符串,比如“Hello World”。
以前在 Objective-C 中,我可以像这样在 AppDelegate 中这样做:
- (void)applicationWillEnterForeground:(UIApplication *)application {
self.viewController.myLabel.text=@"Hello World";
}
但我正在努力让它在 Swift 的 Xcode 6 中工作。因为 AppDelegate 没有设置 View Controller 的实例,所以我在 AppDelegate 中定义了它:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var vc: ViewController=ViewController()
然后尝试同样的方法:
func applicationWillEnterForeground(application: UIApplication) {
vc.myLabel.text="Hello World"
}
但是当我运行该应用程序时, View 显示正常,然后我点击主页,然后返回该应用程序,然后我收到错误消息“ fatal error :在展开可选值时意外发现 nil”
所以我知道 UILabel 是可选的,我收到此错误是因为它的值为 nil。但是我不明白为什么它的值是 nil 因为 View 已经加载了。我尝试使用 applicationDidBecomeActive 得到相同的结果。我不能在我的 ViewController 类中使用 viewDidLoad 或 viewWillAppear,因为当应用程序从后台移动到前台状态时不会调用这些方法。
也将此更新为
if vc.myLabel != nil {
vc.myLabel.text="Hello World"
}
果然 if 语句是假的。
关于如何在 Xcode 6 和 Swift 中重置 UI 元素的任何想法?谢谢。
最佳答案
你的问题是这一行-
var vc: ViewController=ViewController()
分配一个新的 ViewController
实例。它不提供对从您的 Storyboard中显示的实例的引用,并且由于该实例不是从 Storyboard场景中初始化的,因此所有 IBOutlet
都是 nil。
我建议您解耦您的应用程序委托(delegate)和您的 View Controller 并利用
UIApplicationWillEnterForegroundNotification
.
在 View Controller 初始化的某处添加
NSNotificationCenter.defaultCenter().addObserver(self, selector: "enterForeground", name:UIApplicationWillEnterForegroundNotification, object: nil)
然后声明一个函数来处理事件
func enterForeground {
self.myLabel.text="Hello world"
}
关于ios - Xcode 6 swift : Trying to reset IBOutlets in AppDelegate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26079609/