Skip to content

Commit

Permalink
fix: selection coordinates on iOS
Browse files Browse the repository at this point in the history
  • Loading branch information
kirillzyusko committed Jan 14, 2025
1 parent 3410d6d commit f795343
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 20 deletions.
45 changes: 25 additions & 20 deletions ios/delegates/KCTextInputCompositeDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
1 change: 1 addition & 0 deletions ios/protocols/TextInput.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}

Expand Down

0 comments on commit f795343

Please sign in to comment.