Search Unity

ui button dynamic height

Discussion in 'UGUI & TextMesh Pro' started by imaewyn, Sep 3, 2016.

  1. imaewyn

    imaewyn

    Joined:
    Apr 23, 2016
    Posts:
    211
    There is Panel with Vertical Layout Group with button inside it. Button Text can consists one or two strings and different font size. How can I stretch button based on text height? I've tried to add Content Size Fitter on text. but it's not working
     
  2. takatok

    takatok

    Joined:
    Aug 18, 2016
    Posts:
    1,496
    To get a Button to do the following: (Note this is for a fresh UI Button. Remove anything you modified so far)
    1. Add a Horizontal Layout Group to the button
    2. Add A Content Size Fitter To the Button. Set Horizontal and Vertical fit both to Preferred Size
    Your Button will now make its width and Height the same size as the Text tells it. This leads to one small problem. Often this max is exact so the Text will appear to be slightly off the button on the edges. We fix this with some empty pads:

    1. Make 2 Empty GameObjects as childs of the button. They will be siblings of the Text component.
    2. Move One of them before the Text Component.. So the hiearchy is GameObject -- Text -- GameObject
    3. Add a Layout Element to Each GameObject. Check Min Width and set it somewhere between 3-10
    Now your text is padded and the button will shrink and grow both vertically and Horizontally.

    If you only want the button to grow Vertically, Then you need to change the Content Size Fitter Horizontal Fit Setting from Preferred to Unconstrained. The button will now gets its width Information based on how your Panel's Vertical Layout group is telling it to do. If you have Force Expand Width on in your Vertical Layout group of the Panel, the Button will always be as wide as your panel. If you want it to just be a fixed width, You can turn off Force Expand (the button will now shrink to 0). Then add a Layout Element to the button, and set its min Width to what you want.
     
    imaewyn likes this.
  3. imaewyn

    imaewyn

    Joined:
    Apr 23, 2016
    Posts:
    211
    Thank you. It works