As You Type Formatter
As You Type Formatter。通过假设文本始终处于正确状态,这个库旨在进行最小的状态更改;只在使用多个文本属性或现有文本需要更改时重写文本更改过程。
- 高性能 -
O(newText.count + nextWord.count)
最坏情况。 - 自定义 - 提供自己的字符前缀和格式。
- 建议 - 当自定义词已被选中时进行检测,以及替换这些词的方法。
- 代理 - 在使用不同文本格式时检测,并需要新生成建议的方法。
需求
- iOS 8.0+ / tvOS 9.0+
- Xcode 10.3+
- Swift 4.2+
安装
CocoaPods
CocoaPods 是 Cocoa 项目的依赖管理器。有关使用和安装说明,请访问他们的网站。要将 AsYouTypeFormatter 集成到您的 Xcode 项目中使用 CocoaPods,在 Podfile
中指定它
pod 'AsYouTypeFormatter'
Carthage
Carthage 是一种去中心化的依赖管理工具,它为您构建依赖并提供二进制框架。要将 AsYouTypeFormatter 集成到您的 Xcode 项目中并使用 Carthage,请在您的 Cartfile
中指定它。
github "philip-bui/as-you-type-formatter"
Swift Package Manager
Swift Package Manager 是一种自动化分发 Swift 代码的工具,集成到 swift
编译器中。它处于早期开发阶段,但 AsYouTypeFormatter 支持在受支持的平台上使用它。
一旦您设置好 Swift 包,将 AsYouTypeFormatter 添加为依赖项就像将它添加到您的 Package.swift
中 dependencies
值一样简单。
dependencies: [
.package(url: "https://github.com/philip-bui/as-you-type-formatter.git", from: "1.1.0"))
]
使用方法
-
字符前缀。默认
#
@
,以字符前缀开头的单词使用其指定的文本属性。 -
分隔符。默认为表情符号和非字母数字字符,分隔符指示何时使用正常文本属性结束一个单词。
AsYouTypeFormatter 覆盖了两个 UITextView
方法,textView(shouldChangeTextIn:text:)
和 textViewDidChangeSelection()
。您可以将您的 UITextView
委托或在自己定义的委托中调用这些方法。
import AsYouTypeFormatter
// AppDelegate.swift - Modify global defaults.
AsYouTypeFormatter.normalAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)]
AsYouTypeFormatter.tagAttributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16)]
AsYouTypeFormatter.mentionAttributes = [NSAttributedString.Key.font: UIFont.italicSystemFont(ofSize: 16)]
// ViewController.swift - Customize own character prefixes and formats.
private lazy var typeFormatter: AsYouTypeFormatter = {
// Implicit return.
AsYouTypeFormatter(delegate: self, attributes: [
"#": [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16)],
nil: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)]
])
}()
设计决策
- 默认分隔符。默认分隔符是表情符号,以及不在 Unicode 类别 L* 或 0-9 中的字符。委托方法可以自定义此设置。
- 不支持
UITextField
的建议。建议支持依赖于检测用户是否选择了新的单词,而UITextFieldDelegate
并没有暴露文本选择事件。 - 支持链接。启用可选择和可点击的文本不是很实用。
- 在多文本选择时,建议被禁用。假设通常是用户选择文本以复制和粘贴。
许可证
AsYouTypeFormatter 采用 MIT 许可。有关详细信息,请参阅LICENSE。