测试测试 | ✓ |
语言语言 | SwiftSwift |
许可 | MIT |
发布上次发布 | 2017年11月 |
SwiftSwift 版本 | 4.0 |
SPM支持 SPM | ✗ |
由 Ryo Ishikawa 维护。
RegeributedTextView
是 UITextView
的子类,支持基于正则表达式的完全属性字符串。
import RegeributedTextView
您可以将 RegeributedTextView
作为 UITextView
的子类在 Interface Builder 中使用。
使用属性字符串很简单。
更改文字颜色
textView.addAttribute(.all, attribute: .textColor(.red)))
您可以使用正则表达式而不是 .all
。
textView.addAttribute(".*", attribute: .textColor(.red)))
如果您想突出显示提及和哈希标签,就像在 SNS 中一样,可以使用以下参数。
textView.addAttribute(.mention, attribute: .bold))
textView.addAttribute(.hashTag, attribute: .textColor(.blue)))
属性 | 类型 |
---|---|
backgroundColor | UIColor |
bold | - |
boldWithFontSize | CGFloat |
font | UIFont |
fontName | String |
fontSize | CGFloat |
italic | CGFloat |
linkColor | UIColor |
shadow | Shadow |
strikeColor | UIColor |
strikeWithThickness | CGFloat |
strokeWidth | CGFloat |
textColor | UIColor |
underline | UnderlineStyle |
underlineColor | UIColor |
在 Swift 4 中,UITextView
的 linkTextAttributes
属性可以指定链接文本行为,但无法在相同文本中单独为少量文本着色。
在这种情况下,您可以使用类似的正则表达式属性文本。
例如,单独设置文字颜色。
textView.addAttribute("@[a-zA-Z0-9]+", attributes: [.textColor(.black), .bold], values: ["Type": "Mention"])
textView.addAttribute("#[a-zA-Z0-9]+", attribute: .textColor(.blue), values: ["Type": "HashTag"])
在 RegeributedTextView
中,所有带属性的文本都可以通过点击来检测每个单词。
并且您可以检测通过 RegeributedTextViewDelegate
的链接文本的点击事件。values
的参数可以包含任何值。
func regeributedTextView(_ textView: RegeributedTextView, didSelect text: String, values: [String : Any]) {
print("Selected word: \(text)")
if let url = values["Type"] as? String {
// Do something
}
public func addAttribute(_ regexString: String, attribute: TextAttribute, values: [String: Any] = [:], priority: Priority = .medium, applyingIndex: ApplyingIndex = .all)
为了控制属性文本,您可以使用 Priority
和 ApplyingIndex
。
Priority
表示属性字符串的优先级。
属性文本范围有时会重叠,因此此属性可以像 AutoLayout
一样控制属性字符串的优先级。
规则
Applying Index
表示应该应用属性到哪个文本,因为使用正则表达式单独控制属性文本顺序比较困难。
例如,仅应用第一个元素
let userName = "rinov"
textView.addAttribute(userName, attribute: .bold, applyingIndex: .first)
ApplyingIndex
可用的模式如下。
ApplyingIndex | 描述 |
---|---|
all | 应用所有匹配的文本 |
first | 仅应用第一个元素 |
firstFrom(Int) | 从文本起始索引处应用指定数量的次数 |
ignoreFirstFrom(Int) | 从文本起始位置忽略指定的次数 |
最后 | 仅应用最后一个元素 |
从文本末尾索引开始应用指定次数 | 从文本末尾索引开始应用指定次数 |
从文本末尾索引开始忽略指定次数 | 从文本末尾索引开始忽略指定次数 |
indexOf(Int) | 仅应用指定的索引 |
忽略指定的索引 | 仅忽略指定的索引 |
Swift 4
XCode 9
Cocoapods
$: pod repo update
pod "RegeributedTextView"
Swift3.x: pod "RegeributedTextView", "~> 0.1.1"
Swift4.x: pod "RegeributedTextView", "~> 0.2.1"
并且
$: pod install
或
Carthage
github "rinov/RegeributedTextView"
并且
$: carthage update --platform iOS
rinov, [email protected]
RegeributedTextView遵循MIT许可证。更多信息请参阅LICENSE文件。