[Xcode 实际操作]九、实用进阶-(14)使用富文本CoreText框架创建丰富多彩的文本

目录:[Swift]Xcode实际操作

本文将演示如何使用富文本CoreText框架创建丰富多彩的文本图形。

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

 1 import UIKit
 2 //导入需要用到的富文本CoreText框架
 3 import CoreText
 4 
 5 class ViewController: UIViewController {
 6 
 7     override func viewDidLoad() {
 8         super.viewDidLoad()
 9         // Do any additional setup after loading the view, typically from a nib.
10         
11         //初始化一个标签对象,并设置其位置在(10,60),尺寸为(300,40)。
12         let label = UILabel(frame: CGRect(x: 10, y: 60,  300, height: 40))
13         //创建一个字体对象,并设置其字体和大小
14         let font = CTFontCreateWithName(("ArailMT" as CFString?)!, 32, nil)
15         
16         //创建一个可变属性字符串,可以对属性字符串,同时添加多个样式属性
17         let string = NSMutableAttributedString(string: "My name is strengthen!")
18         //给字符串开始位置之后的11个字符,设置自定义的字体样式
19         string.addAttribute(kCTFontAttributeName as NSAttributedString.Key,
20          value: font, 
21          range: NSRange(location: 0, length: 11))
22         
23         //给字符串开始位置之后的11个字符,设置文字为红色
24         string.addAttribute(kCTForegroundColorAttributeName as NSAttributedString.Key,
25          value: UIColor.red,
26          range: NSRange(location: 0, length: 11))
27         
28         //创建一个数字变量
29         var number = 3
30         //将数字转换为CF数字类型。
31         let cfNumber = CFNumberCreate(kCFAllocatorDefault, CFNumberType.sInt8Type, &number)
32         //然后对第12个字符之后的9个字符,进行宽度为3的描边处理。
33         string.addAttribute(kCTStrokeWidthAttributeName as NSAttributedString.Key, 
34          value: cfNumber!, 
35          range: NSMakeRange(12, 9))
36         
37         //初始化一个大小为14的斜体字体
38         let italicFont = UIFont.italicSystemFont(ofSize: 14)
39         //将字体对象转换为CTFont类型。
40         let fontValue = CTFontCreateWithName(italicFont.fontName as CFString, 14, nil)
41         //将第22个字符之后的3个字符,设置大小为14的斜体字符
42         string.addAttribute(kCTFontAttributeName as NSAttributedString.Key, 
43          value: fontValue, 
44          range: NSRange(location: 22, length: 3))
45         
46         //将第26个字符之后的5个字符,添加宽度为1的下划线
47         string.addAttribute(kCTUnderlineStyleAttributeName as NSAttributedString.Key,
48          value: NSNumber(value: 1),
49          range: NSRange(location: 26, length: 5))
50         
51         //将可变属性字符串,赋予标签对象的属性文本属性
52         label.attributedText = string
53         self.view.addSubview(label)
54     }
55     
56     override func didReceiveMemoryWarning() {
57         super.didReceiveMemoryWarning()
58         // Dispose of any resources that can be recreated.
59     }
60 }

CFIndex:typedef signed long CFIndex

在Core Foundation框架中一般用于数组的序号和参数返回值的大小,计数等。

Core Foundation中CFIndex的位长随着处理器的位长而增加。

如64位机器中CFIndex可能就为64位,而和int的位长无关。

所以在与Core Foundation的交互中,使用CFIndex将有很好的可移植性,建议使用。

原文地址:https://www.cnblogs.com/strengthen/p/10089292.html