Created
March 15, 2018 15:31
-
-
Save rnkyr/b2943e88b041aadd0739677e98223f8c to your computer and use it in GitHub Desktop.
An example on how to setup links inside UITextView
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
| // | |
| // PrivacyTableViewCell.swift | |
| // | |
| // Created by Roman Kyrylenko on 5/22/17. | |
| // Copyright © 2017 pr0ctopus. All rights reserved. | |
| // | |
| private let privacyScheme = "privacy" | |
| private let termsScheme = "terms" | |
| final class PrivacyTableViewCell: UITableViewCell, UITextViewDelegate, NibReusable { | |
| @IBOutlet private var textView: UITextView! | |
| private var field: PrivacyAndTermsFormField? | |
| func setup(with field: PrivacyAndTermsFormField) { | |
| self.field = field | |
| setup(textView) | |
| } | |
| private func setup(_ textView: UITextView) { | |
| let termsPart = tr(.textTermsOfService) | |
| let privacyPart = tr(.textPrivacyPolicy) | |
| let template = tr(.textTermsAndPrivacy(termsPart, privacyPart)) | |
| let attributedString = NSMutableAttributedString(string: template) | |
| let string = template as NSString | |
| attributedString.addAttribute( | |
| NSLinkAttributeName, | |
| value: "\(termsScheme)://", | |
| range: string.range(of: termsPart) | |
| ) | |
| attributedString.addAttribute( | |
| NSLinkAttributeName, | |
| value: "\(privacyScheme)://", | |
| range: string.range(of: privacyPart) | |
| ) | |
| let paragraph = NSMutableParagraphStyle() | |
| paragraph.alignment = .center | |
| paragraph.lineBreakMode = .byWordWrapping | |
| paragraph.maximumLineHeight = 17 | |
| paragraph.minimumLineHeight = 17 | |
| attributedString.addAttributes( | |
| [ | |
| NSFontAttributeName: FontFamily.SFUIText.light.font(size: 11), | |
| NSParagraphStyleAttributeName: paragraph, | |
| NSForegroundColorAttributeName: UIColor.blackPearl.withAlphaComponent(0.7) | |
| ], | |
| range: NSRange(location: 0, length: string.length) | |
| ) | |
| textView.attributedText = attributedString | |
| textView.linkTextAttributes = [ | |
| NSForegroundColorAttributeName: UIColor.blackPearl, | |
| NSFontAttributeName: FontFamily.SanFranciscoText.semibold.font(size: 11) | |
| ] | |
| textView.delegate = self | |
| textView.isEditable = false | |
| } | |
| // MARK: - UITextViewDelegate | |
| func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool { | |
| guard let scheme = URL.scheme else { | |
| return true | |
| } | |
| if scheme == privacyScheme { | |
| field?.privacyAction.onNext() | |
| } else if scheme == termsScheme { | |
| field?.termsAction.onNext() | |
| } else { | |
| return true | |
| } | |
| return false | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment