我在
Swift(XCode 6.2)中制作了一个非常简单的单视图应用程序,它包含2个按钮“blackButton”和“whiteButton”.点击blackButton后,将View的背景颜色更改为Black,单击whiteButton后,将背景更改为白色.任何人都可以提出任何可能的方法来做到这一点吗?
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. } }
解决方法
视图控制器的视图可以通过它的view属性访问,它只是一个常规的UIView. UIView有一个backgroundColor属性,它是一个UIColor并控制视图的颜色.
@IBAction func blackButton(sender: AnyObject) { self.view.backgroundColor = UIColor.blackColor() } @IBAction func whiteButton(sender: AnyObject) { self.view.backgroundColor = UIColor.whiteColor() }