2017-07-31 28 views
0

我需要從全局範圍更改故事板上的標籤的功能。如何從全球範圍更改出口屬性?

當我嘗試運行此代碼,我得到的錯誤是:

fatal error: unexpectedly found nil while unwrapping an Optional value 

的問題是,viewController.congratulations爲空。

如何解決這個問題?提前致謝!

func myAlert() 
{ 
    // how to change 'configuration.text' from here? 

    let storyboard = UIStoryboard(name: "Main", bundle: nil); 
    let viewController : ViewController = storyboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController; 

    viewController.congratulations.text = "test"; 
} 

class ViewController: UIViewController 
{ 
    @IBOutlet weak var congratulations: UILabel!; 

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

     myAlert(); 
    } 

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

} 
+0

筆尖加載後,插座獲取UI的引用,所以它始終爲零。 –

+0

在這裏你再次按照我在'viewDidLoad' myAlert();' –

+0

的理解進行再次探討爲什麼myAlert定義在你的類的範圍之外? –

回答

1

你不應該直接嘗試從它被定義在類的外部訪問UILabel。只有在您的UIViewController子類的特定實例上調用viewDidLoad後纔會創建標籤。

你應該做的是將你想要在你的標籤上顯示的文本存儲在另一個變量中,並從你的課堂外改變這個變量。

+0

我應該使用計時器來檢查它是否已更改? –

+0

絕對不是。你可以使用財產觀察員來做這件事。 –

0

名爲congratulations的IBOutlet在viewDidLoad中爲零。因此,請在ViewController(例如stringValue)處創建一個String屬性。設置該字符串的特性,同時導航

在你的viewController的viewDidLoad方法,得到了stringValue的,並將其值標註

self.congratulations.text = stringValue; 
0

添加myAlert()到的ViewController類解決了這個問題。

class ViewController: UIViewController 
{ 
    func myAlert() 
    { 
     self.congratulations.text = "vrebreberbfrbb"; 
    } 

    @IBOutlet weak var congratulations: UILabel!; 

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

     myAlert(); 
    } 

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

}