Created
December 11, 2018 22:29
-
-
Save bright23/bbc0d4c78cb203f54f8f4fb18895969b to your computer and use it in GitHub Desktop.
HTTPSLinkTextViewSample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
``` 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