Swift - 从函数更新UILabel

问题描述 投票:-2回答:1

我正在制作一个蓝牙应用程序,我想要控制两个标签,如果我已连接并显示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:]

但是当我旋转手机时它会更新标签,我试图在我的标签前加上“自我”。 我也尝试在一个计时器内调用我的函数,但它给了我一个SIGBART错误 那么有更新标签或重新加载viewcontroller的方法吗?

编辑:调用我的功能:

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

    RSSINb = Int(RSSI) * -1
    updateLabel()
    if(RSSINb > 150){
        WriteValue(valeur: "z")
    }
}
ios swift multithreading uilabel cbperipheral
1个回答
0
投票

问题解决了:

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")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.