2017-06-04 17 views
1

我試圖用不同類中檢索到的數據更新UILabel,因此在ViewDidLoad中,我調用了該不同類中的方法,然後在該類中,在ViewController中調用一個方法來更新UILabel。下面是我試圖運行的代碼的簡化版本:無法在不同類中調用不同方法後更改UILabel

import UIKit 

    class ViewController: UIViewController { 

    @IBOutlet var label: UILabel! 
    override func viewDidLoad() { 
    super.viewDidLoad()   
    test().runTest() 
} 

func print() { 
    label.text = "test123" 
} 

} 

和其他類:

import UIKit 

class test: UIView { 

    func runTest() { 
     ViewController().print() 
    } 
} 

我不斷收到話說打印到控制檯上的錯誤消息:「致命錯誤:意外地發現零,而 「關於

而一個錯誤」 label.text = 「test123」 展開可選的值(LLDB)說: 「線程1:EXC_Bad_Instruction(代碼= EXC_(386_INVOP,子碼=爲0x0)」

預先感謝您的幫助。

+0

您是否將插座連接到故事板中的標籤? – StevenOjo

+1

在你的'runTest'函數中,你正在創建視圖控制器的一個新實例,並且你沒有參考故事板就這麼做,所以標籤出口是零。當您調用視圖控制器實例時,可以將視圖控制器實例傳遞給'runTest',或者,最好讓'runTest'返回值並讓視圖控制器本身負責更新其標籤。這是一個糟糕的設計,有一個類更新其他類視圖 – Paulw11

+0

你如何組織你的視圖控制器,我可能也建議重命名你的功能。 – joshLor

回答

0
Your label IBOutlet is nil because you are creating a new viewcontroller instance and your viewcontroller is not attached any story board. you can pass self to  func runTest() and on self you can call print. Hope it will help! 

You can use this 

import UIKit 

    class ViewController: UIViewController { 

    @IBOutlet var label: UILabel! 
    override func viewDidLoad() { 
    super.viewDidLoad()   
    test().runTest(self) 
} 

func print() { 
    label.text = "test123" 
} 

} 

import UIKit 

class test: UIView { 

    func runTest(controller:ViewController) { 
     controller.print() 
    } 
} 
+0

完美!它現在有效。謝謝! – Mark

0

你的問題是,你正在你的視圖控制器的新實例上運行的功能,而你應該在已經創建的實例上運行它。例如,如果你的視圖是你的視圖控制器的孩子,你可以這樣做,在你的類test替換編輯你的功能測試是這個。

func runTest() { 
    if let vc = self.parent as? ViewController{ 
     vc.print() 
    } 
} 

這應該在已經創建的視圖控制器實例上運行該函數。

相關問題