Swift - 如何从函数更新 UILabel
Swift - How to update UILabel from a function
我正在制作一个蓝牙应用程序,我想放置 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:]
但是当我旋转 phone 它更新标签时,我试图将 'self' 放在我的标签之前。
我还尝试在计时器中调用我的函数,但它给了我一个 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")
}
}
编辑:
What's the proper way in architecture design to avoid UI API to be called on a background thread?
已解决的问题:
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")
}
}
我正在制作一个蓝牙应用程序,我想放置 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:]
但是当我旋转 phone 它更新标签时,我试图将 'self' 放在我的标签之前。
我还尝试在计时器中调用我的函数,但它给了我一个 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")
}
}
编辑:
What's the proper way in architecture design to avoid UI API to be called on a background thread?
已解决的问题:
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")
}
}