RegeributedTextView 0.2.1

RegeributedTextView 0.2.1

测试测试
语言语言 SwiftSwift
许可 MIT
发布上次发布2017年11月
SwiftSwift 版本4.0
SPM支持 SPM

Ryo Ishikawa 维护。



  • rinov

RegeributedTextView

Build Status
Cocoapods
Carthage
License
Platform
[Language

RegeributedTextViewUITextView 的子类,支持基于正则表达式的完全属性字符串。

DEMO

用法

import RegeributedTextView

您可以将 RegeributedTextView 作为 UITextView 的子类在 Interface Builder 中使用。

InterfaceBuilder

使用属性字符串很简单。

更改文字颜色

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 中,UITextViewlinkTextAttributes 属性可以指定链接文本行为,但无法在相同文本中单独为少量文本着色。
在这种情况下,您可以使用类似的正则表达式属性文本。

例如,单独设置文字颜色。

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)

为了控制属性文本,您可以使用 PriorityApplyingIndex
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文件。