SemanticString
SemanticString
是一个字符串抽象,其中包括有关文本结构语义的信息。这些信息允许对文本应用样式,形成 NSAttributedString
类型的结果。
基本用法。
在例子中,我们创建带高亮单词 "world" 的文本 "hello world!"
let text = SemanticString("Hello \(style: .bold, "world")!")
// or let text = SemanticString(xml: "Hello <bold>world</bold>!")
// object that provides text attributes
let provider = SemanticStringAttributesProvider(
commonAttributes: [.font: UIFont.systemFont(ofSize: 14)],
styleAttributes: [
.bold: [.font: UIFont.boldSystemFont(ofSize: 14)]
]
)
let attributedText = text.getAttributedString(provider: provider)
要求
- Swift 5.1
安装
CocoaPods
# Podfile
use_frameworks!
target 'YOUR_TARGET_NAME' do
pod 'SemanticString'
end
Swift Package Manager
在XCode中选择文件/Swift Packages/添加包依赖。输入'SemanticString',选择SemanticString
项目,然后点击'下一步'、'下一步'。
R.swift一起使用
与如果您的应用应在运行时支持更改语言,R.swift可以用于方便地访问字符串资源。SemanticString
从字符串资源创建而不依赖于区域设置,并且可用于更新屏幕上的文本。这允许您从服务提供语言无关的字符串,从而无需重新计算数据即可刷新UI。
添加符合SemanticString.StringResourceType
的Rswift.StringResource
的代码
import Rswift
import protocol SemanticString.StringResourceType
extension Rswift.StringResource: StringResourceType { }
使用示例
let string = SemanticString(resource: R.string.localizable.helloWorld)
print(string)
SemanticString.setCurrentLocale(Locale(identifier: "ru-RU"))
print(string)
提示:使用typealias
缩短字符串资源路径。
typealias Strings = R.string.localizable