Is it possible to get the UDim2 of the TextBox cursor?

Looking to implement my own Textbox cursor, but was wondering how to get the UDim2 position of the text cursor. Not talking about CursorPosition.

There’s no built-in way to reliably achieve this. Best you can do is use a monospace font to know the width of each character and use that to determine the absolute position of the cursor based on the CursorPosition property. That requires quite a bit of effort, as you may need to take word wrap into account which definitely doesn’t make things any simpler.

Fixed it by doing this:

local function getCursorPosition()
        local textbox = TextBox
        local cursorPosition = textbox.CursorPosition
        local font = textbox.Font
        local fontSize = textbox.TextSize
        local text = textbox.Text
        local padding = textbox.UIPadding

        local xOffset = padding.PaddingLeft.Offset + textbox.AbsolutePosition.X
        local yOffset = padding.PaddingTop.Offset + textbox.AbsolutePosition.Y - fontSize

        local cursorXOffset = TextService:GetTextSize(string.sub(text, 1, cursorPosition), fontSize, font, Vector2.new(10000, 10000)).X
        local cursorYOffset = TextService:GetTextSize(string.sub(text, 1, cursorPosition), fontSize, font, Vector2.new(10000, 10000)).Y

        local cursorUDim = UDim2.new(0, cursorXOffset + xOffset, 0, cursorYOffset + yOffset)
        return cursorUDim
    end
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.