Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift hiding label when a button is pressed

I have created my own label and my own button. Now when the page loads the label hides as I want but when i click the button it does not show up as it supposed to do, in fact it does not do anything. How can I fix this problem which is making label show when i press the button?

 @IBOutlet var thumbsUpButtonaPressed : UIButton!

    @IBOutlet weak var label : UILabel!


override func viewDidLoad() {
        var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
        label.center = CGPointMake(160, 284)
        label.textAlignment = NSTextAlignment.Center
        label.text = "00000"
        self.view.addSubview(label)

       label.hidden = true




   let buttona = UIButton()
        buttona.frame = CGRectMake(0.772 * view.bounds.width, 0.32 * view.bounds.height, 22, 22)
        buttona.layer.cornerRadius = 0.04 * view.bounds.width
        buttona.backgroundColor = UIColor.greenColor()
        buttona.setImage(UIImage(named:"A.png"), forState: .Normal)
        buttona.addTarget(self, action: "thumbsUpButtonaPressed", forControlEvents: .TouchUpInside)
        view.addSubview(button)


     func thumbsUpButtonaPressed(sender: UIButton!) {

            label.hidden = false



    }
  }
like image 578
A. stein Avatar asked May 07 '16 13:05

A. stein


3 Answers

I am using below code on swift 3

label.isHidden = true // hide
label.isHidden = false // show

you can use isHidden with other ui objects, see that answer also

like image 105
Ulug'bek Avatar answered Nov 02 '22 07:11

Ulug'bek


Create an IBAction:

@IBAction func thumbsUpButtonaPressed(sender: UIButton) {
    label.hidden = false
}

Then connect it with your button by cmd + drag on the button to the action:

image

Swift 5 Update

@IBAction func thumbsUpButtonaPressed(sender: UIButton) {
    label.isHidden = false
}
like image 34
Pranav Wadhwa Avatar answered Nov 02 '22 06:11

Pranav Wadhwa


Unless I am missing something in viewDidLoad you are creating a new label

 var label = ...

you are not using the IBOutlet Property like

 label = ...

Also are you sure your brackets are correct because it looks like your buttonPressed method is nested inside viewDidLoad.

like image 2
crashoverride777 Avatar answered Nov 02 '22 08:11

crashoverride777