View not refreshed when calling UIButton.isHidden = true / false
I am using xcode 8.2
and swift
to create a simple application.
I added UIButton
to my view using Interface Builder
.
I've added the appropriate outputs for the button:
@IBOutlet weak var myBtn: UIButton!
I want this button to be hidden on startup, so in viewDidLoad
I am setting the value Hidden
. Like this:
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 (getting a specific message using MQTT), I get printouts, but I can't see the button. If I click the Where I Know button, then the button appears.
Any idea what might be going on here? I spent an hour googling it now! Please do not suggest a object-c
way to solve this problem as I do not know object-c
.
source to share
Since you are calling a service, you may not be working on the same thread. Try the following:
func showHideButton(){
DispatchQueue.main.async {
if (self.showButton ) {
print("button enabled!")
self.myBtn.isHidden = false
} else {
print("button disabled!")
self.myBtn.isHidden = true
}
}
}
source to share