Last active
October 15, 2019 02:46
-
-
Save hsleedevelop/9f664b0dc6a36db5666cbce78b1fb3d6 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
typealias CustomLabelTouchHandler = (CustomLabel) -> Void | |
typealias CustomLabelTouchIndexHandler = (CustomLabel, Int) -> Void | |
private var touchHandler: CustomLabelTouchHandler? | |
private var touchHandlerWithIndex: CustomLabelTouchIndexHandler? | |
///Never ever use ide attribute text, then will trigger correctly | |
@objc func didLabelTouchedWidthIndexHandler(_ gestureRecognizer: UIGestureRecognizer) { | |
guard let attributedString = self.attributedText, let font = self.font else { return } | |
let mutableAttribString = NSMutableAttributedString(attributedString: attributedString) | |
mutableAttribString.addAttributes([NSAttributedString.Key.font: font], range: NSRange(location: 0, length: attributedString.length)) //!important | |
let storage = NSTextStorage(attributedString: mutableAttribString) | |
let layoutManager = NSLayoutManager() | |
storage.addLayoutManager(layoutManager) | |
let container = NSTextContainer(size: .init(width: self.bounds.size.width, height: self.bounds.size.height)) | |
container.lineFragmentPadding = 0 | |
container.lineBreakMode = self.lineBreakMode | |
container.maximumNumberOfLines = self.numberOfLines | |
layoutManager.addTextContainer(container) | |
let locationInLabel = gestureRecognizer.location(in: gestureRecognizer.view) | |
let indexOfCharacter = layoutManager.characterIndex(for: locationInLabel, in: container, fractionOfDistanceBetweenInsertionPoints: nil) | |
var i = 0 | |
outer: for touchText in touchTexts { | |
if let text = self.text, let regex = try? NSRegularExpression(pattern: touchText, options: []) { | |
let matches = regex.matches(in: text, options: [], range: NSMakeRange(0, text.count)) | |
for match in matches { | |
if NSLocationInRange(indexOfCharacter, match.range) { | |
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { | |
self.touchHandlerWithIndex?(self, i) | |
} | |
break outer | |
} | |
} | |
} | |
i += 1 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment