Skip to content

Instantly share code, notes, and snippets.

@xavierjurado
Created April 16, 2019 07:08
Show Gist options
  • Save xavierjurado/c8036c3f15e2fa0933452270092d88cf to your computer and use it in GitHub Desktop.
Save xavierjurado/c8036c3f15e2fa0933452270092d88cf to your computer and use it in GitHub Desktop.
class MyViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
let htmlString = """
<a style="text-decoration:none; font-weight:bold;" href="https://verse.me/en/faq">How Verse takes care of your money</a>
"""
let textView = ExternalLinkTextView(htmlString: htmlString)
view.addSubview(textView)
textView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
textView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
self.view = view
}
}
class ExternalLinkTextView: UIView, UITextViewDelegate {
private let textView = UITextView()
init(htmlString: String) {
super.init(frame: .zero)
translatesAutoresizingMaskIntoConstraints = false
addSubview(textView)
NSLayoutConstraint.activate([
textView.leftAnchor.constraint(equalTo: leftAnchor),
textView.rightAnchor.constraint(equalTo: rightAnchor),
textView.topAnchor.constraint(equalTo: topAnchor),
textView.bottomAnchor.constraint(equalTo: bottomAnchor),
])
// TODO: avoid force unwraps
let data = htmlString.data(using: .utf8)!
let attributedString = try! NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
textView.attributedText = attributedString
textView.isEditable = false
textView.isScrollEnabled = false
textView.delegate = self
textView.translatesAutoresizingMaskIntoConstraints = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
print(URL)
return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment