@@ -35,15 +35,10 @@ extension NSTextLineFragment {
35
35
for index in ( start..< length) . reversed ( ) {
36
36
let point = locationForCharacter ( at: index)
37
37
38
- if span. upperBound > point. x {
38
+ if span. upperBound >= point. x {
39
39
end = min ( index + 1 , length)
40
40
break
41
41
}
42
-
43
- if span. upperBound == point. x {
44
- end = index
45
- break
46
- }
47
42
}
48
43
49
44
guard let end else { return nil }
@@ -85,16 +80,24 @@ extension NSTextLayoutFragment {
85
80
precondition ( location >= 0 )
86
81
precondition ( location != NSNotFound)
87
82
83
+ var locationOffset = location
84
+
88
85
for textLineFragment in textLineFragments {
86
+ // we have to shift to compute overlap, and then shift back to compute the span
89
87
let bounds = textLineFragment. typographicBounds. offsetBy ( dx: origin. x, dy: origin. y)
90
-
91
- let overlap = bounds. intersection ( rect)
88
+ let overlap = bounds. intersection ( rect) . offsetBy ( dx: - origin. x, dy: - origin. y)
92
89
let span : Range < CGFloat > = overlap. minX..< overlap. maxX
93
90
91
+ // the locationOffset has to be computed even if we do not overlap
92
+ let offset = locationOffset
93
+ defer {
94
+ locationOffset += textLineFragment. characterRange. length
95
+ }
96
+
94
97
guard let localRange = textLineFragment. rangeOfCharacters ( intersecting: span) else { continue }
95
98
96
99
let range = NSRange (
97
- location: localRange. location + location ,
100
+ location: localRange. location + offset ,
98
101
length: localRange. length
99
102
)
100
103
0 commit comments