Change the View BackgroundColor on Tap

441 Views Asked by At

I want to change the text and the background color of the view on tap. The quotes are changing, but the view background color don't change. What am I doing wrong?

Here is the code:

import UIKit        // UI: user interface

class ViewController: UIViewController {

// IB: Interface Builder
@IBOutlet weak var quoteLabel: UILabel!

var quotes = Quotes()


// gets called when the view is loaded
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

// Interface Builder Action.
// Gets called whenever the user taps on the button
@IBAction func inspireMeDidTap(sender: UIButton)
{
    let quote = quotes.randomQuote()
    quoteLabel.text = quote

    // change the background color of the view
    view.backgroundColor = randomColor()
}

func randomColor() -> UIColor
{
    let random = Int(arc4random()) % 5  // 0 -> 4
    switch random {
    case 0: return UIColor(red: 211/255.0, green: 86/255.0, blue: 87/255.0, alpha: 0)
    case 1: return UIColor(red: 71/255.0, green: 178/255.0, blue: 137/255.0, alpha: 0)
    case 2: return UIColor(red: 229/255.0, green: 177/255.0, blue: 93/255.0, alpha: 0)
    case 3: return UIColor(red: 92/255.0, green: 163/255.0, blue: 178/255.0, alpha: 0)
    case 4: return UIColor(red: 38/255.0, green: 38/255.0, blue: 38/255.0, alpha: 0)
    default: return UIColor(red: 56/255.0, green: 72/255.0, blue: 72/255.0, alpha: 0)
    }

}

}
2

There are 2 best solutions below

0
On BEST ANSWER

try this:

put all alpha = 1 in your colors (instead of 0). If alpha = 0, entirely transparent

Meaning of alpha

0
On

You are setting alpha parameter to zero it means whatever the color is it will be completely transperent(not white).

So what you need to do is just set alpha to 1 and you will get your correct color