[Xcode 实际操做]7、文件与数据-(19)颜色集(Color Set)的使用

目录:[Swift]Xcode实际操做html

本文将演示颜色集合的使用。swift

使用颜色集合能够很方便地建立应用程序的主题色,而且能够方便的对主题颜色进行更换。ide

要使用颜色集功能,须要设置项目的部署(Deployment)版本号。post

【Deployment Target】:选择11.0以上的选项。spa

接着打开资源文件夹,在资源文件夹中建立颜色集合。code

【Assets.xcassets】->【+】->【New Color Set】->htm

点击修改颜色的默认名称:BackgroundColor对象

->打开属性设置面板->点击刚才新建的图标,切换至颜色设置面板。blog

颜色集合的默认颜色为白色,能够修改红、绿、蓝颜色通道的数值资源

->使用相同的方式,建立第二个颜色集合。

【Assets.xcassets】->【+】->【New Color Set】->

点击修改颜色的默认名称:ForegroundColor

在项目导航区,打开视图控制器的代码文件【ViewController.swift】

 1 import UIKit
 2 
 3 class ViewController: UIViewController {
 4 
 5     override func viewDidLoad() {
 6         super.viewDidLoad()
 7         // Do any additional setup after loading the view, typically from a nib.
 8         
 9         //建立一个标签对象,它的显示区域和根视图相同,
10         let lbl = UILabel(frame: self.view.frame)
11         
12         //添加一个版本兼容性的判断语句
13         if #available(iOS 11.0, *)
14         {
15             //分别设置两个颜色集合
16             //做为标签对象的背景颜色
17             lbl.backgroundColor = UIColor(named: "BackgroundColor")
18             //做为标签对象的文字颜色
19             lbl.textColor = UIColor(named:"ForegroundColor")
20         }
21         
22         //设置标签对象的文字内容
23         lbl.text = "https://www.cnblogs.com/strengthen/"
24         //设置标签对象的文字对齐方式
25         lbl.textAlignment = .center
26         
27         //将标签对象添加到当前视图控制器的根视图
28         self.view.addSubview(lbl)
29     }
30     
31     override func didReceiveMemoryWarning() {
32         super.didReceiveMemoryWarning()
33         // Dispose of any resources that can be recreated.
34     }
35 }

颜色背景也能够应用在故事版中,在故事版中设置根视图的背景颜色。

首先清除标签对象的背景颜色。

使用快捷键【Command】+【/】注释标签背景颜色:

//lbl.backgroundColor = UIColor(named: "BackgroundColor")

接着打开并编辑故事版文件【main.storyboard】

选择当前视图控制器的根视图。

打开右侧的属性设置面板,设置:

【Background】:在颜色面板中,显示了刚自定义的两个颜色集合。选择其中一个。

相关文章
相关标签/搜索