get the width of user input in a native.textfield - solution ok?

Dear Corona community,

my native.textfield has a fixed width and I’d like to shrink the fontsize according to user inputlength so that userinput is always visible and not cropped on x-axis. Basically I’m looking for a :resizeFontToFitWidth() solution.

This is how I detect the width of the input:

userInput = native.newTextField( … )

userInput:resizeFontToFitHeight()

invisibleText = display.newText("", 0,0, native.systemFontBold, userInput.size)

So, I have a newText object with an empty string that has the same fontsize as my native.newTextField.

Now, within the “editing” event.phase of the native.newTextField, I do the following:

invisibleText.text = event.text

inputWidth = invisibleText.width

So, I copy the user’s input into my invisible text and get it’s width from there. That works, the only question is: Isn’t there a simpler solution? To me it seems that this is way too complicated, but I couldnt figure out any other way to achieve this.

Thanks for your help :slight_smile:

Your method actually seems to be the best I can think of, since there is no “width handling” API for native inputs.

A related question is, what happens if your user continues to keep typing and typing? Eventually the text will get so small, they can’t really read it, correct? If you keep scaling it down as they type more, eventually that would happen… personally, I’m not sure I would like that user experience when using the app…

Best regards,

Brent

Thank you Brent, so I’ll leave it that way.

In my editing phase I also check for the length of the input:

if(string.len(event.text) > 35) then 

         event.target.text = string.sub(event.text, 1, 35)
end

:slight_smile:

Your method actually seems to be the best I can think of, since there is no “width handling” API for native inputs.

A related question is, what happens if your user continues to keep typing and typing? Eventually the text will get so small, they can’t really read it, correct? If you keep scaling it down as they type more, eventually that would happen… personally, I’m not sure I would like that user experience when using the app…

Best regards,

Brent

Thank you Brent, so I’ll leave it that way.

In my editing phase I also check for the length of the input:

if(string.len(event.text) > 35) then 

         event.target.text = string.sub(event.text, 1, 35)
end

:slight_smile: