简体   繁体   中英

Xcode Swift button hidden

I have two buttons in VC. Button1 and Button2.

I also have one string variable "buttonToHide". With some logic, I am finding the button to hide and hence buttonToHide = "Button2"

Now I want to hide that actual Button2 using the string var buttonToHide. How do I do that?

Button2.hidden = true is great but I need to use string to do that functionality.

Thanks very much !!

 @IBOutlet var Button1: UIButton!
    @IBOutlet var Button2: UIButton!
    @IBOutlet var Button3: UIButton!
    @IBOutlet var Button4: UIButton!

var ArrayHere = ["1","2","3","4"]

        var noEmptyStrings = ArrayHere.filter({$0 != "\(self.CorrectAnswer)"})

        let randomIndex = Int(arc4random_uniform(UInt32(noEmptyStrings.count)))

        var noEmptyStrings1 = noEmptyStrings.filter({$0 != "\(noEmptyStrings[randomIndex])"})


        var firstValue = "Button" + noEmptyStrings1.first!
        var lastvalue = noEmptyStrings1.last

        println("\(firstValue)")
        println("\(lastvalue)")

        firstValue.hidden = true  //THIS IS NOT WORKING

You should store your buttons in an Array of Buttons. For example:

var myButtons = [UIButton]()

So you are able to filter Buttons for properties (to get the correct button, or use the key of array)

For example:

myButtons[1].hidden = true

Rather than maintaining arrays and dealing with outlet collections, you might consider using tag s, an admittedly somewhat quaint but nevertheless intriguingly simple mechanism.

Give your buttons these tags in Interface Builder, eg 1 to 4. They will allow you to access these buttons easily.

Then you do not need a string to store the button to hide, just an Int . The following will hide the button to be hidden and unhide all other buttons.

for i in 1...4 {
   let button = view.viewWithTag(i) as! UIButton
   button.hidden = i == toHide
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM