MicrosoftDave MicrosoftDave - 2 months ago 12
iOS Question

Toggle hidden state of UILabel

I want to use the press of a button to toggle the hidden state of a couple of UILabels. Press the button once, it unhides them, press again the labels are hidden, the default state for these labels being hidden.

Here is what I thought would work (but obviously does not):

@IBAction func information(sender: AnyObject, forEvent event: UIEvent)
{
if(infoLocation.hidden = true)
{
self.infoLocation.hidden = false
}
else
{
self.infoLocation.hidden = true
}

//**********************************//
if(infoName.hidden = true)
{
self.infoName.hidden = false
}
else
{
self.infoName.hidden = true
}

//**********************************//
if(infoVersion.hidden = true)
{
self.infoVersion.hidden = false
}
else
{
self.infoVersion.hidden = true
}


}

Answer

To make the code shorter (and look better) I would do like this if its just a toggle:

for label in [label1, label2, label3, label4] {
    label.hidden = !label.hidden
}

This will toggle label1-4.hidden