Search code examples
iosswiftxcodeswift3arc4random

Show buttons randomly by pressing them


I want to have six buttons in my project and want them to be always hidden except one. And when I press the button that is not hidden it should be hidden and another button should randomly appear and do the same. Would appreciate if someone could help me!!


Solution

  • Create six buttons in your Storyboard, add a tag to them and then create one Action outlet that you connect all buttons to and then do the following:

    @IBAction func button_clicked(_ sender: AnyObject) {
        // generate a random number which is not the same as the tag that you 
        repeat{
            random = Int(arc4random_uniform(6) + 1)
        }
        while random == sender.tag
    
        // iterate through all subviews in your view to find all buttons
        for view in self.view.subviews{
            // make sure it´s a button
            if view.isKind(of: UIButton.self){
                // create a button from the view you're iterating to
                let button = view as! UIButton
                // if the button tag is equal to the random number you just created we want to show that button 
                if button.tag == random{
                    button.isHidden = false
                }
                // else hide it
                else{
                    button.isHidden = true
                }
            }
        }
    }
    

    Here is a sample project I created that does this that you can try. Make sure though to read the comments in the code above and understand what´s happening.