Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Background Color of ViewController Swift? (Single View Application)

I am making a very simple single view application in Swift (XCode 6.2) that comprises of 2 buttons "blackButton" and "whiteButton". Upon clicking blackButton it changes the View's background color to Black and upon clicking the whiteButton it changes the background to white. Can anyone suggest any possible ways to do this?

ViewController.swift:

//beginning
import UIKit

class ViewController: UIViewController {

    @IBAction func blackButton(sender: AnyObject) {
    }
    @IBAction func whiteButton(sender: AnyObject) {
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}
like image 710
MarcB1 Avatar asked Apr 20 '15 22:04

MarcB1


People also ask

How do I change the background color in Viewcontroller?

Find the view or view controller you want to change the background color of. Open it up in the interface builder and open the Attributes Inspector. Find the background color field and set it to the color you want.

How do I change the background color in Xcode?

At the top select the attributes inspector. Under the section "View" there should be a spot that says "Background". click that and choose your colour.


3 Answers

A view controller's view can be accessed through it's view property, which is just a regular UIView. UIView's have a backgroundColor property, which is a UIColor and controls the color of the view.

@IBAction func blackButton(sender: AnyObject) {
   view.backgroundColor = .black
}

@IBAction func whiteButton(sender: AnyObject) {
   view.backgroundColor = .white
}
like image 52
nhgrif Avatar answered Oct 07 '22 14:10

nhgrif


For Custom Colors

@IBAction func blackButton(sender: AnyObject) {
    let blackColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
    view.backgroundColor = blackColor 
 }

@IBAction func whiteButton(sender: AnyObject) {
    let whiteColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0)
    view.backgroundColor = whiteColor
}
like image 43
Museer Ahamad Ansari Avatar answered Oct 07 '22 15:10

Museer Ahamad Ansari


You can also use Color Literal. Easily to customize your own colors.

@IBAction func blackButton(sender: AnyObject) {
    view.backgroundColor = ColorLiteral   //Custom color
}

@IBAction func whiteButton(sender: AnyObject) {
    view.backgroundColor = ColorLiteral   //Custom color
}
like image 1
Jacob Ahlberg Avatar answered Oct 07 '22 15:10

Jacob Ahlberg