Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View is not being updated when calling UIButton.isHidden = true/false

I am using xcode 8.2 and swift to make a simple application.

I have added a UIButton to my View using the 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:

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.

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.

like image 387
theAlse Avatar asked Mar 24 '17 12:03

theAlse


3 Answers

In onMessageCallback block

Replace following line

self.showHideSeatButtons()

with

DispatchQueue.main.async {
    self.showHideSeatButtons()
}

Note: UI related changes/updates must be handled by main queue (thread).

like image 125
Krunal Avatar answered Nov 08 '22 18:11

Krunal


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
            }
        }
    }
like image 23
Hapeki Avatar answered Nov 08 '22 18:11

Hapeki


try this

myBtn.isHidden = true
myBtn.alpha = 0
like image 1
chris Avatar answered Nov 08 '22 17:11

chris