Reputation: 249
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.
}
}
Upvotes: 22
Views: 47172
Reputation: 62052
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
}
Upvotes: 37
Reputation: 2792
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
}
Upvotes: 1
Reputation: 5523
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
}
Upvotes: 7