【问题标题】:Swift - How to update UILabel from a functionSwift - 如何从函数更新 UILabel
【发布时间】:2019-03-18 01:12:29
【问题描述】:

我正在制作一个蓝牙应用程序,我想放置 2 个标签来控制我是否已连接并显示 RSSI,所以我编写了这个函数

func updateLabel(){
    LRSSI.text = String(RSSINb)
    if(Connected == true){
        LEtat.text = "Connected"
        LEtat.textColor = UIColor.green
    }else{
        LEtat.text = "Disconnected"
        LEtat.textColor = UIColor.red
    }
}


我在 CBPeripheral 的 ReadRSSI 函数中调用此函数。
我的终端里有这段文字

Main Thread Checker: UI API called on a background thread: -[UILabel setText:]

但是当我旋转手机时,它会更新标签,我试图将“self”放在标签之前。
我也尝试在计时器内调用我的函数,但它给了我一个 SIGBART 错误
那么有没有办法更新标签或重新加载视图控制器?

编辑: 调用我的函数:

 func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {
    print(RSSI)
    peripheral.readRSSI()

    RSSINb = Int(RSSI) * -1
    updateLabel()
    if(RSSINb > 150){
        WriteValue(valeur: "z")
    }
}

编辑:

What's the proper way in architecture design to avoid UI API to be called on a background thread?

【问题讨论】:

标签: ios swift multithreading uilabel cbperipheral


【解决方案1】:

问题已解决:

func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {
    print(RSSI)
    peripheral.readRSSI()

    RSSINb = Int(RSSI) * -1
    DispatchQueue.main.sync {
        updateLabel()
    }
    if(RSSINb > 150){
        WriteValue(valeur: "z")
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多