brownmamba
brownmamba

Reputation: 173

Removing a UILabel programmatically after a button is pressed

I am trying to create/show a label when a button is pressed, and then delete/hide the same label when the same button is pressed again. I am trying to do this all programmatically in Swift.

I have tried using label.removeFromSuperview() but it doesn't seem to have any effect. However when i try removing the button in the same code location using button.removeFromSuperview()

var label = UILabel()
let labelImage = UIImage(named: "Strike Line.png")


/* to select checkmarked state */
func pressCheck() {

    let image = UIImage(named: "Checkmark.png")
    button.setBackgroundImage(image, for: UIControlState.normal)
    button.addTarget(self, action:#selector(self.pressUnCheck), for: .touchUpInside)
    self.view.addSubview(button)


    textField1.textColor = UIColor.gray //change textfield to a gray color

    label = UILabel(frame: CGRect(x : 31, y : 69, width: 200, height: 2))

    label.backgroundColor = UIColor(patternImage: labelImage!)
    self.view.addSubview(label)
}


func pressUnCheck()
{
    let image = UIImage(named: "To Be Completed Circle.png")
    button.setBackgroundImage(image, for: UIControlState.normal)
    button.addTarget(self, action:#selector(self.pressCheck), for: .touchUpInside)
    self.view.addSubview(button)


    label.removeFromSuperview()
    textField1.textColor = UIColor.black

}

Here is where i am trying to remove/hide the label.

Upvotes: 0

Views: 1575

Answers (2)

mrabins
mrabins

Reputation: 197

There's a few ways to handle this... If you just want to hide it you can use

label.isHidden = true - would hide the label. label.isHidden = false - would show the label.

Upvotes: 1

Micah Wilson
Micah Wilson

Reputation: 1482

Since this apparently was the fix I'll drop it in as an answer.

Add button.removeTarget(nil, action: nil, for: .allEvents) before you add any new targets to your button.

If you don't remove the current target it'll have multiple targets and be calling both pressCheck() and pressUnCheck() on each button press.

Upvotes: 1

Related Questions