Skip to content

Instantly share code, notes, and snippets.

@bright23
Created December 11, 2018 22:29
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 bright23/bbc0d4c78cb203f54f8f4fb18895969b to your computer and use it in GitHub Desktop.
Save bright23/bbc0d4c78cb203f54f8f4fb18895969b to your computer and use it in GitHub Desktop.
HTTPSLinkTextViewSample
``` swift
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
let baseText = "apple https://www.apple.com/jp/ thanks https://qiita.com/shtnkgm/items/3c8b6b794219fbf087ba"
let words: [String] = baseText
.components(separatedBy: .whitespacesAndNewlines)
var linkTexts: [String] = []
words.forEach { if $0.hasPrefix("https://") { linkTexts.append($0) } }
let attributedString = NSMutableAttributedString(string: baseText)
linkTexts.forEach { attributedString.addAttribute(.link,
value: $0,
range: NSString(string: baseText).range(of: $0)) }
textView.attributedText = attributedString
textView.isSelectable = true
textView.delegate = self
}
}
extension UIViewController: UITextViewDelegate {
private func textView(_ textView: UITextView,
shouldInteractWith URL: URL,
in characterRange: NSRange,
interaction: UITextItemInteraction) -> Bool {
UIApplication.shared.open(URL)
return false
}
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment