# Making a dialog that expands to fit its text

I'm trying to make an OK/Cancel-style dialog which will expand to fit its text in Unity 5.6. I've been trying to pull this off using Unity's built-in UI layout components, but so far I haven't been able to get it exactly right.

The dialog has a background, a title, a body, and two buttons. The goal is for the dialog to resize itself vertically to fit the length of the text. Here is an example with placeholder graphics:

I have this almost working properly, but I created it by abusing the built-in layout components and it doesn't always behave properly. Here's how it's currently set up:

• Background is an Image
• Vertical Layout Group:
• Control Child Size: Width
• Content Size Fitter:
• Horizontal Fit: Unconstrained
• Vertical Fit: Min Size

Background has the following children:

• Title is a Text
• Body is a Text
• Content Size Fitter
• Horizontal Fit: Unconstrained
• Vertical Fit: Preferred Size
• Buttons is a GameObject
• Horizontal Layout Group
• Child Force Expand: Width and Height

This setup works about 90% of the time, with the dialog properly resizing according to the text. However, at certain (seemingly arbitrary) body lengths, an extra blank line will be added to the Body text, which disrupts the vertical spacing and gives the dialog a strange look:

This isn't too surprising, because you're not supposed to put a Content Size Fitter on a child of a Layout Group; however, I couldn't figure out any other way to get the dialog to vertically expand to fit more text. Is there a better way to handle this?

You can use the text object's preferredWidth and prefferedHeight values to do this.
My code includes a value for creating a ratio in the end result's width and height, but if you are only expanding the height, all you need to do is call SetSizeWithCurrentAnchors vertically and it should expand to the necessary height.