AttributedStringBuilder
AttributedStringBuilder 可以减轻创建 NSAttributedStrings 的痛苦。
- 更易于阅读的
NSAttributedString
创建 - 不再需要与属性字典纠缠
- 轻松在字符串中渲染图像
- 'Swifty' 接口
使用方法
导入 AttributedStringBuilder 模块
import AttributedStringBuilder
创建一个字符串
AttributedStringBuilder 的函数总是返回您正在使用的 AttributedStringBuilder
实例,因此您可以通过连续调用函数来编写简洁、易读的代码。
使用枚举案例及其相关值定义属性
可以设置默认属性,并覆盖选定的文本部分。
let builder = AttributedStringBuilder()
builder.defaultAttributes = [
.textColor(UIColor.black),
.font( UIFont.systemFont(ofSize: 16, weight: UIFontWeightRegular) ),
.alignment(.center),
]
builder
.text("Attributed strings can make")
.space()
.text("specific words", attributes: [.textColor(UIColor.red)])
.space()
.text("pop out")
builder.attributedString
另一个例子
通过链式调用方法,可以仅用几行代码创建复杂的AttributedStrings
let builder = AttributedStringBuilder()
builder.defaultAttributes = [
.alignment(.center),
.textColor(UIColor.orange),
.font( UIFont(name: "AvenirNext-Bold", size: 30)! )
]
builder
.text("It's ")
.text("Easy ", attributes: [.underline(true), .textColor(UIColor.blue)])
.text("To ", attributes: [.strokeWidth(2), .textColor(UIColor.black)])
.text("Adjust ", attributes: [.skew(0.3), .textColor(UIColor.magenta)])
.text("Attributes ", attributes: [.font(UIFont(name: "Baskerville-Bold", size: 30)!)])
builder.attributedString
更复杂的例子
// Create an AttributedStringBuilder with default attributes
let builder = AttributedStringBuilder()
builder.defaultAttributes = [.alignment(.center)]
// First line attributes
let titleAttributes: [AttributedStringBuilder.Attribute] = [
.font(UIFont(name: "Futura-Bold", size: 40)!),
.textColor(UIColor.white),
.strokeColor(UIColor.magenta),
.strokeWidth(-8),
.kerning(5)
]
// Second Line Attributes
let canDoAttributes: [AttributedStringBuilder.Attribute] = [
.font(UIFont(name: "Marker Felt", size: 30)!),
.textColor(UIColor.orange),
.kerning(5)
]
// Third Line Attributes
let shadow = NSShadow()
shadow.shadowColor = UIColor.black
shadow.shadowBlurRadius = 5
let awesomeAttributes: [AttributedStringBuilder.Attribute] = [
.font(UIFont(name: "AvenirNext-Bold", size: 40)!),
.textColor(UIColor.yellow),
.kerning(5),
.shadow(shadow),
.skew(0.3),
.underline(true)
]
// Build the string
builder
.text("ATTRIBUTED STRINGS", attributes: titleAttributes)
.newline()
.text("Can do", attributes: canDoAttributes)
.newline()
.text("AWESOME THINGS", attributes: awesomeAttributes)
builder.attributedString
图片
在您的字符串中渲染图片非常容易,可以根据字体的大写或小写高度调整其大小
let font = UIFont.systemFont(ofSize: 90)
let builder = AttributedStringBuilder()
builder.defaultAttributes = [
.font(font),
.underline(true),
.textColor(UIColor.purple)
]
let image = UIImage(named: "PurpleMonster")!
builder
.image(image, withSizeFittingFontUppercase: font)
.text("Hello")
.image(image, withSizeFittingFontLowercase: font)
安装
CocoaPods
将以下行添加到您的Podfile中
pod "AttributedStringBuilder"
手动
将AttributedStringBuilder.swift
复制到您的项目中
谁?
许可
AttributedStringBuilder遵循MIT许可。有关更多信息,请参阅LICENSE文件。