- Home /
SelectableLabel or TextArea in Scrollview
While using a Textarea with a Scrollview works great in Unity 3.5, it does not work well in Unity 3.4. I am developing a script that requires a scrollable label that is selectable. A standard label works well with the scrollview, but a selectable label or text area will not expand the scrollview controls. Any ideas on how this can be achieved in Unity 3.4?
Answer by absameen · May 20, 2012 at 11:44 PM
Was finally able to figure this one out. Create a GUIStyle called textStyle and use textStyle.CalcSize to size the TextArea based on the content inside of it. This will allow you to scroll it with a scroll view:
scrollView = EditorGUILayout.BeginScrollView(scrollView, false, false);
Vector2 textSize = textStyle.CalcSize(new GUIContent(myString));
EditorGUILayout.TextArea(codeCache, textStyle, GUILayout.ExpandHeight(true), GUILayout.ExpandWidth(true), GUILayout.MinWidth(textSize.x), GUILayout.MinHeight(textSize.y));
EditorGUILayout.EndScrollView();
Answer by yoyo · May 09, 2014 at 12:43 AM
Thanks @absameen for putting me on the right track. In my case I wanted to deal with word wrap as well, so I needed to use CalcHeight, not CalcSize. This requires knowing the width of the current draw area, which required jumping through a couple of extra hoops.
Here is the final result, a helper method for drawing multi-line selectable text inside a scroll area:
private Vector3 ScrollableSelectableLabel(Vector3 position, string text, GUIStyle style)
{
// Extract scroll position and width from position vector.
Vector2 scrollPos = new Vector2(position.x, position.y);
float width = position.z;
scrollPos = GUILayout.BeginScrollView(scrollPos);
// Calculate height of text.
float pixelHeight = style.CalcHeight(new GUIContent(text), width);
EditorGUILayout.SelectableLabel(text, Styles.info, GUILayout.MinHeight(pixelHeight));
// Update the width on repaint, based on width of the SelectableLabel's rectangle.
if (Event.current.type == EventType.Repaint)
{
width = GUILayoutUtility.GetLastRect().width;
}
GUILayout.EndScrollView();
// Put scroll position and width back into the Vector3 used to track position.
return new Vector3(scrollPos.x, scrollPos.y, width);
}
Thanks for posting this. I'm also trying to get a scrollable SelectableLabel, but it doesn't seem to be displaying the scroll bars, for some reason. I think the key is to use a correct style. What style are you using? 'Styles.info' doesn't seem to be anything recognizable for me - it must be your type, right? If so, what styling did you exactly use? I based my style on textArea, which works fine with scrollbars, but I don't want the editing features.