ios - 在不同类中调用不同方法后无法更改方法中的 UILabel

标签 ios swift uilabel

我正在尝试使用从不同类检索到的数据更新 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/

相关文章:

ios - 具有恒定大小和动态字体大小的 UILabel 取决于文本

ios - 在警报中点击 Return Key Tap 时的操作

ios - 在PFQueryTableViewController中删除单元格和[self loadObjects]时,它在-[UITableView _endCellAnimationsWithContext:]中出现断言失败。

ios - Swift (XCode) - sigabrt 错误

ios - 检查 UITableViewAutomaticDimension 返回 -1

ios - iPhone - 从 UILabel 中的链接中删除下划线

ios - Swift 3 中的 UILongPressGestureRecognizer

ios - 如何在特定索引处显示 UITabBarController?

swift - 如何将私有(private)函数变成辅助函数?

ios - Objective-C 默认启用自动收缩