Skip to content

Instantly share code, notes, and snippets.

@rinov
Created June 11, 2017 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rinov/d95bc4a2b7fda0e730d5b3c383e9a65d to your computer and use it in GitHub Desktop.
Save rinov/d95bc4a2b7fda0e730d5b3c383e9a65d to your computer and use it in GitHub Desktop.
UITextViewで複雑なHighlightを表現する ref: http://qiita.com/rinov/items/da450d0ba9dffaaf8967
textView.text = "Hello World"
let attributedText = textView.mutableCopy() as? NSMutableAttributedString
attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSMakeRange(0, 5))
textView.attributedText = attributedText
// 単語ごとに個別の指定は行えない
textView.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.red]
textView.addAttribute("Hello", attribute: .textColor(.red))
func addAttribute(_ regexString: String,
attribute: TextAttribute,
values: [String: Any] = [:],
priority: Priority = .medium,
applyingIndex: ApplyingIndex = .all)
// 対象の文字列を指定する
textView.addAttribute("#general", attribute: .textColor(.red))
// RegexStringTypeから選択する
textView.addAttribute(.hashTag, attribute: .textColor(.red))
// 正規表現で指定する
textView.addAttribute("#[a-zA-Z0-9]", attribute: .textColor(.red))
//Delegateを指定:(例)class HogeViewController: RegeributedTextViewDelegate
textView.delegate = self
// Value付きで装飾を行う
textView.addAttribute("#general", attribute: .textColor(.red), value: ["URL": "https://hoge.com"])
// 属性テキストがタップされた時に呼ばれるDelegate
func regeributedTextView(_ textView: RegeributedTextView, didSelect text: String, values: [String: Any]) {
guard let url = values["URL"] as? String else { return }
print(url)
// Do something
}
textView.addAttributes("#general", attributes: [.bold, .fontSize(16), .textColor(.black)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment