4
$\begingroup$

I'd like to have an InputField that adjusts its size to the content. I can't make ImageSize->{All, All} or anything similar to work.

I was trying to play with FEPrivate`StringWidth but I am not sure what does it return. It is neither in px nor in em so the solution below leaves an offset which varies with the string size but with types of characters used aswell:

DynamicModule[{x = "test"}
, InputField[Dynamic[x], String
  , FieldSize -> {.5 + 1.5 Dynamic@FEPrivate`StringWidth[x][[1]], 1}
  , ContinuousAction -> True
  , BaseStyle -> 12
  ]
]

Is there a solution to this problem?

$\endgroup$
  • 1
    $\begingroup$ Assuming the font is a fixed width font, can't you just use something like: .5 + .56 Dynamic@StringLength[x], which works well on my MacBook. $\endgroup$ – Carl Woll Oct 26 '18 at 19:14
  • $\begingroup$ At least for me, your code uses a fixed width font. If I change the base style so that a proportional font is used, e.g., "Times", then your code works fine as well (with a 1. scaling factor instead of 1.5). Could you provide the font that you want to use? $\endgroup$ – Carl Woll Oct 26 '18 at 19:21
  • $\begingroup$ @CarlWoll It seems I have confused things and your code does fit my needs. Feel free to post it as an answer. Somehow I assumed a string length will be less accurate. $\endgroup$ – Kuba Oct 26 '18 at 19:26
1
$\begingroup$

You may use the {min, max} syntax for FieldSize.

InputField[Dynamic[x], String, FieldSize -> {{20, 40}, {1, \[Infinity]}}]

The above creates an InputField that is initially 20-by-1. It can expand to fit its contents up to 40 wide and infinitely tall.

Hope this helps.

$\endgroup$
  • 1
    $\begingroup$ Wow, FieldSize -> {{1, \[Infinity]}, {1, 1}} is exactly what I need. Somehow I failed to grasp it when I was reading docs. I was trying things like {1, All} which work as min/max spec for ImageSize elsewhere. $\endgroup$ – Kuba Oct 26 '18 at 21:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.