xcode 调用 UIButton.isHidden = true/false 时未更新视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42999646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
View is not being updated when calling UIButton.isHidden = true/false
提问by theAlse
I am using xcode 8.2
and swift
to make a simple application.
我正在使用xcode 8.2
并swift
制作一个简单的应用程序。
I have added a UIButton
to my View using the Interface Builder
.
我已经UIButton
使用Interface Builder
.
I have added the appropriate outlets for the button:
我为按钮添加了适当的插座:
@IBOutlet weak var myBtn: UIButton!
I want this button to be hidden on start so in viewDidLoad
I am setting is to Hidden
. Like this:
我希望这个按钮在开始时隐藏,所以在viewDidLoad
我的设置中是Hidden
. 像这样:
override func viewDidLoad() {
super.viewDidLoad()
...
myBtn.isHidden = true
...
mqttConfig = MQTTConfig(clientId: "iphone7", host: "192.xx.xx.150", port: 18xx, keepAlive: 60)
mqttConfig.onMessageCallback = { mqttMessage in
if ( mqttMessage.topic == "status" ) {
if ( mqttMessage.payloadString?.localizedStandardContains("show") )! {
self.showButton = true
} else if ( mqttMessage.payloadString?.localizedStandardContains("hide") )! {
self.showButton = false
}
self.showHideSeatButtons()
} else {
// something to do in case of other topics
}
}
Later in the code I have a function to show/hide this button.
在代码的后面,我有一个显示/隐藏这个按钮的功能。
func showHideButton(){
if ( self.showButton ) {
print("button enabled!")
myBtn.isHidden = false
} else {
print("button disabled!")
myBtn.isHidden = true
}
}
When I call this function (by receiving a certain message using MQTT) I get the print outs but I don't see the button. If I press where I know the button is, then the button gets shown.
当我调用这个函数时(通过使用 MQTT 接收某个消息),我得到了打印输出,但我没有看到按钮。如果我按下我知道按钮所在的位置,那么按钮就会显示出来。
Any idea what could be going on here? I have spent and hour googling this now! Please don't suggest object-c
way of solving this issue, as I don't know object-c
.
知道这里会发生什么吗?我现在已经花了一个小时在谷歌上搜索这个!请不要建议object-c
解决这个问题的方法,因为我不知道object-c
。
采纳答案by Krunal
In onMessageCallback block
在 onMessageCallback 块中
Replace following line
替换以下行
self.showHideSeatButtons()
with
和
DispatchQueue.main.async {
self.showHideSeatButtons()
}
Note: UI related changes/updates must be handled by main queue (thread).
注意:UI 相关的更改/更新必须由主队列(线程)处理。
回答by Hapeki
Since you're calling a service it's possible you're not working in the same thread. Try this:
由于您正在调用服务,因此您可能不在同一个线程中工作。尝试这个:
func showHideButton(){
DispatchQueue.main.async {
if (self.showButton ) {
print("button enabled!")
self.myBtn.isHidden = false
} else {
print("button disabled!")
self.myBtn.isHidden = true
}
}
}