Created
July 2, 2019 07:15
-
-
Save kingiol/11cf131a2f8bf11673d85ebafe7d3a78 to your computer and use it in GitHub Desktop.
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
let underlineAttriString = NSMutableAttributedString(string: text) | |
let range1 = (text as NSString).range(of: i18n("AgreementTerms")) | |
underlineAttriString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range1) | |
let range2 = (text as NSString).range(of: i18n("AgreementPrivacy")) | |
underlineAttriString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range2) | |
self.agreeLabel.attributedText = underlineAttriString | |
@IBAction func tapLabelDetect(_ gesture: UITapGestureRecognizer) { | |
let text = self.agreeLabel.text ?? "" | |
let termsRange = (text as NSString).range(of: i18n("AgreementTerms")) | |
let privacyRange = (text as NSString).range(of: i18n("AgreementPrivacy")) | |
if gesture.didTapAttributeTextInLabel(self.agreeLabel, inRange: termsRange) { | |
print("tap terms") | |
} else if gesture.didTapAttributeTextInLabel(self.agreeLabel, inRange: privacyRange) { | |
print("tap privacy") | |
} else { | |
} | |
} | |
extension UITapGestureRecognizer { | |
func didTapAttributeTextInLabel(_ label: UILabel, inRange targetRange: NSRange) -> Bool { | |
let layoutManager = NSLayoutManager() | |
let textContainer = NSTextContainer(size: .zero) | |
let textStorage = NSTextStorage(attributedString: label.attributedText ?? NSAttributedString(string: "")) | |
layoutManager.addTextContainer(textContainer) | |
textStorage.addLayoutManager(layoutManager) | |
textContainer.lineFragmentPadding = 0.0 | |
textContainer.lineBreakMode = label.lineBreakMode | |
textContainer.maximumNumberOfLines = label.numberOfLines | |
let labelSize = label.bounds.size | |
textContainer.size = labelSize | |
let locattionOfTouchInLabel = self.location(in: label) | |
let textBoundingBox = layoutManager.usedRect(for: textContainer) | |
let textContainerOffset = CGPoint(x: (labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, | |
y: (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y) | |
let locationOfTouchInTextContainer = CGPoint(x: locattionOfTouchInLabel.x - textContainerOffset.x, | |
y: locattionOfTouchInLabel.y - textContainerOffset.y) | |
let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, | |
in: textContainer, | |
fractionOfDistanceBetweenInsertionPoints: nil) | |
return NSLocationInRange(indexOfCharacter, targetRange) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment