[Xcode10 实际操作]七、文件与数据-(19)颜色集(Color Set)的使用

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

使用颜色集合可以很方便地创建应用程序的主题色,并且可以方便的对主题颜色进行更换。

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

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

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

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

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

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

颜色集合的默认颜色为白色,可以修改红、绿、蓝颜色通道的数值

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

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

扫描二维码关注公众号,回复: 4327589 查看本文章

点击修改颜色的默认名称: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】:在颜色面板中,显示了刚自定义的两个颜色集合。选择其中一个。

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10052190.html