Skip to content

Commit 35fe03a

Browse files
committed
fix: selection coordinates on iOS
1 parent 6e7c2db commit 35fe03a

File tree

2 files changed

+26
-20
lines changed

2 files changed

+26
-20
lines changed

ios/delegates/KCTextInputCompositeDelegate.swift

+25-20
Original file line numberDiff line numberDiff line change
@@ -5,30 +5,35 @@
55
// Created by Kiryl Ziusko on 24/04/2024.
66
//
77

8+
import CoreText
89
import Foundation
910

1011
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),
2729
],
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+
]
3237
}
3338

3439
func updateSelectionPosition(textInput: UITextInput, sendEvent: (_ event: NSDictionary) -> Void) {

ios/protocols/TextInput.swift

+1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ public protocol TextInput: UIView {
1414
var inputView: UIView? { get set }
1515
var keyboardType: UIKeyboardType { get }
1616
var keyboardAppearance: UIKeyboardAppearance { get }
17+
var font: UIFont? { get }
1718
func focus()
1819
}
1920

0 commit comments

Comments
 (0)