ios 更改 ViewController Swift 的背景颜色?(单视图应用程序)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29759224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:43:20  来源:igfitidea点击:

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

iosswiftuiviewcontroller

提问by MarcB1

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?

我正在 Swift (XCode 6.2) 中制作一个非常简单的单视图应用程序,它包含 2 个按钮“blackButton”和“whiteButton”。单击 blackButton 后,它将视图的背景颜色更改为黑色,单击 whiteButton 后,它将背景更改为白色。谁能建议任何可能的方法来做到这一点?

ViewController.swift:

视图控制器.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.
    }


}

回答by nhgrif

A view controller's view can be accessed through it's viewproperty, which is just a regular UIView. UIView's have a backgroundColorproperty, which is a UIColorand controls the color of the view.

视图控制器的视图可以通过它的view属性访问,它只是一个常规的UIView. UIView有一个backgroundColor属性,它是 aUIColor并控制视图的颜色。

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

@IBAction func whiteButton(sender: AnyObject) {
   view.backgroundColor = .white
}

回答by Museer Ahamad Ansari

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
}

回答by Jacob Ahlberg

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
}