From 35fe03a11db69c376aa09d4dc67928b3f71692fa Mon Sep 17 00:00:00 2001 From: kirillzyusko Date: Tue, 14 Jan 2025 14:36:53 +0100 Subject: [PATCH] fix: selection coordinates on iOS --- .../KCTextInputCompositeDelegate.swift | 45 ++++++++++--------- ios/protocols/TextInput.swift | 1 + 2 files changed, 26 insertions(+), 20 deletions(-) diff --git a/ios/delegates/KCTextInputCompositeDelegate.swift b/ios/delegates/KCTextInputCompositeDelegate.swift index 4f0b73929..bdb469a05 100644 --- a/ios/delegates/KCTextInputCompositeDelegate.swift +++ b/ios/delegates/KCTextInputCompositeDelegate.swift @@ -5,30 +5,35 @@ // Created by Kiryl Ziusko on 24/04/2024. // +import CoreText import Foundation func textSelection(in textInput: UITextInput) -> NSDictionary? { - if let selectedRange = textInput.selectedTextRange { - let caretRectStart = textInput.caretRect(for: selectedRange.start) - let caretRectEnd = textInput.caretRect(for: selectedRange.end) - - return [ - "selection": [ - "start": [ - "x": caretRectStart.origin.x, - "y": caretRectStart.origin.y, - "position": textInput.offset(from: textInput.beginningOfDocument, to: selectedRange.start), - ], - "end": [ - "x": caretRectEnd.origin.x + caretRectEnd.size.width, - "y": caretRectEnd.origin.y + caretRectEnd.size.height, - "position": textInput.offset(from: textInput.beginningOfDocument, to: selectedRange.end), - ], + guard let selectedRange = textInput.selectedTextRange, + let input = textInput as? TextInput, + let font = input.font + else { return nil } + + let caretRectStart = textInput.caretRect(for: selectedRange.start) + let caretRectEnd = textInput.caretRect(for: selectedRange.end) + + let ctFont = CTFontCreateWithName(font.fontName as CFString, font.pointSize, nil) + let ascent = CTFontGetAscent(ctFont) + + return [ + "selection": [ + "start": [ + "x": caretRectStart.origin.x, + "y": caretRectStart.origin.y, + "position": textInput.offset(from: textInput.beginningOfDocument, to: selectedRange.start), ], - ] - } - - return nil + "end": [ + "x": caretRectEnd.origin.x + caretRectEnd.size.width, + "y": caretRectEnd.origin.y + caretRectEnd.size.height + ascent, + "position": textInput.offset(from: textInput.beginningOfDocument, to: selectedRange.end), + ], + ], + ] } func updateSelectionPosition(textInput: UITextInput, sendEvent: (_ event: NSDictionary) -> Void) { diff --git a/ios/protocols/TextInput.swift b/ios/protocols/TextInput.swift index 57ff04a36..99f428159 100644 --- a/ios/protocols/TextInput.swift +++ b/ios/protocols/TextInput.swift @@ -14,6 +14,7 @@ public protocol TextInput: UIView { var inputView: UIView? { get set } var keyboardType: UIKeyboardType { get } var keyboardAppearance: UIKeyboardAppearance { get } + var font: UIFont? { get } func focus() }