@@ -118,7 +118,8 @@ final class NitroTextView: UITextView {
118118 var index = glyphRange. location
119119 while index < NSMaxRange ( glyphRange) {
120120 var lineGlyphRange = NSRange ( location: 0 , length: 0 )
121- let usedRect = lm. lineFragmentUsedRect ( forGlyphAt: index, effectiveRange: & lineGlyphRange)
121+ let usedRect = lm. lineFragmentUsedRect (
122+ forGlyphAt: index, effectiveRange: & lineGlyphRange)
122123 let charRange = lm. characterRange ( forGlyphRange: lineGlyphRange, actualGlyphRange: nil )
123124
124125 let substring = fullText. substring ( with: charRange)
@@ -128,7 +129,9 @@ final class NitroTextView: UITextView {
128129 var desc : CGFloat = - ( font? . descender ?? 0 )
129130 var cap : CGFloat = font? . capHeight ?? 0
130131 var xh : CGFloat = font? . xHeight ?? 0
131- if let attrsFont = storage? . attribute ( . font, at: charRange. location, effectiveRange: nil ) as? UIFont {
132+ if let attrsFont = storage? . attribute (
133+ . font, at: charRange. location, effectiveRange: nil ) as? UIFont
134+ {
132135 asc = attrsFont. ascender
133136 desc = - ( attrsFont. descender)
134137 cap = attrsFont. capHeight
@@ -160,8 +163,33 @@ final class NitroTextView: UITextView {
160163 }
161164
162165 @objc private func handleTap( _ recognizer: UITapGestureRecognizer ) {
163- if recognizer. state == . ended {
164- nitroTextDelegate ? . onNitroTextPress ( )
165- }
166+ guard recognizer. state == . ended else { return }
167+ clearSelectionIfNeeded ( at : recognizer . location ( in : self ) )
168+ nitroTextDelegate ? . onNitroTextPress ( )
166169 }
170+
167171}
172+
173+ private extension NitroTextView {
174+ func selectionLength( _ range: UITextRange ) -> Int {
175+ offset ( from: range. start, to: range. end)
176+ }
177+
178+ func isPoint( _ point: CGPoint , insideSelection range: UITextRange ) -> Bool {
179+ for selectionRect in selectionRects ( for: range) {
180+ let rect = selectionRect. rect
181+ if rect. isNull || rect. isEmpty { continue }
182+ if rect. contains ( point) { return true }
183+ }
184+ return false
185+ }
186+
187+ func clearSelectionIfNeeded( at point: CGPoint ) {
188+ guard let currentSelection = selectedTextRange,
189+ selectionLength ( currentSelection) > 0
190+ else { return }
191+ if !isPoint( point, insideSelection: currentSelection) {
192+ selectedTextRange = nil
193+ }
194+ }
195+ }
0 commit comments