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?
//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.
}
}
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.
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.
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
}
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
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With