我正在尝试使用从不同类检索到的数据更新 UILabel,因此在 ViewDidLoad 中,我在该不同类中调用一个方法,然后在该类中调用 ViewController 中的一个方法来更新 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()
}
}
我不断在控制台中收到一条错误消息:“ fatal error :在展开可选值 (lldb) 时意外发现 nil”
“label.text = “test123”上的错误说:“Thread 1: EXC_Bad_Instruction(code=EXC_(386_INVOP, subcode = 0x0)”
预先感谢您的帮助。
最佳答案
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()
}
}
关于ios - 在不同类中调用不同方法后无法更改方法中的 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44350899/