|
5 | 5 | // Created by Kiryl Ziusko on 24/04/2024.
|
6 | 6 | //
|
7 | 7 |
|
| 8 | +import CoreText |
8 | 9 | import Foundation
|
9 | 10 |
|
10 | 11 | func textSelection(in textInput: UITextInput) -> NSDictionary? {
|
11 |
| - if let selectedRange = textInput.selectedTextRange { |
12 |
| - let caretRectStart = textInput.caretRect(for: selectedRange.start) |
13 |
| - let caretRectEnd = textInput.caretRect(for: selectedRange.end) |
14 |
| - |
15 |
| - return [ |
16 |
| - "selection": [ |
17 |
| - "start": [ |
18 |
| - "x": caretRectStart.origin.x, |
19 |
| - "y": caretRectStart.origin.y, |
20 |
| - "position": textInput.offset(from: textInput.beginningOfDocument, to: selectedRange.start), |
21 |
| - ], |
22 |
| - "end": [ |
23 |
| - "x": caretRectEnd.origin.x + caretRectEnd.size.width, |
24 |
| - "y": caretRectEnd.origin.y + caretRectEnd.size.height, |
25 |
| - "position": textInput.offset(from: textInput.beginningOfDocument, to: selectedRange.end), |
26 |
| - ], |
| 12 | + guard let selectedRange = textInput.selectedTextRange, |
| 13 | + let input = textInput as? TextInput, |
| 14 | + let font = input.font |
| 15 | + else { return nil } |
| 16 | + |
| 17 | + let caretRectStart = textInput.caretRect(for: selectedRange.start) |
| 18 | + let caretRectEnd = textInput.caretRect(for: selectedRange.end) |
| 19 | + |
| 20 | + let ctFont = CTFontCreateWithName(font.fontName as CFString, font.pointSize, nil) |
| 21 | + let ascent = CTFontGetAscent(ctFont) |
| 22 | + |
| 23 | + return [ |
| 24 | + "selection": [ |
| 25 | + "start": [ |
| 26 | + "x": caretRectStart.origin.x, |
| 27 | + "y": caretRectStart.origin.y, |
| 28 | + "position": textInput.offset(from: textInput.beginningOfDocument, to: selectedRange.start), |
27 | 29 | ],
|
28 |
| - ] |
29 |
| - } |
30 |
| - |
31 |
| - return nil |
| 30 | + "end": [ |
| 31 | + "x": caretRectEnd.origin.x + caretRectEnd.size.width, |
| 32 | + "y": caretRectEnd.origin.y + caretRectEnd.size.height + ascent, |
| 33 | + "position": textInput.offset(from: textInput.beginningOfDocument, to: selectedRange.end), |
| 34 | + ], |
| 35 | + ], |
| 36 | + ] |
32 | 37 | }
|
33 | 38 |
|
34 | 39 | func updateSelectionPosition(textInput: UITextInput, sendEvent: (_ event: NSDictionary) -> Void) {
|
|
0 commit comments