Author Topic: Correct way to size widget to content  (Read 2407 times)

duncanfoo

  • Guest
Correct way to size widget to content
« on: October 28, 2013, 06:29:20 AM »
I have a widget which contains a table, and a label anchored to the bottom of the table. Like this:

+-------WIDGET----+
|+-------TABLE----+|
||row1                  ||
|+-----------------+|
||row2                  ||
|+-----------------+|
|      SOME LABEL     |
+-------------------+

I want to size the widget to the content. That is as the number of rows in the table determmines the overall height of the widget.

I tried doing it after I added the items to the table. Something like:

  1. GameObject cell = NGUITools.AddChild(_table.gameObject, _darkPrefab);
  2. cell.name = "1";
  3. cell = NGUITools.AddChild(_table.gameObject, _lightPrefab);
  4. cell.name = "2";
  5. _table.Reposition();
  6.  
  7. Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(_label.gameObject.transform);
  8. UIWidget widget = GetComponent<UIWidget>();
  9. widget.height = (int)(bounds.center.y + bounds.extents.y);

The problem here is the label isn't reposition by the anchor until the next update.

I can put the resize code in the update, but I'm not sure that is really correct. Firstly, isn't there an issue with update order? Is there a guarantee that the anchor updates prior to the code which updates the widget? Secondly, I need to actually pad the size a bit since the panel is supposed to be a little taller than the content (think a border top and bottom for a window). If I do something like:

  1.     void Update()
  2.     {
  3.         Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(gameObject.transform);
  4.         Debug.Log(bounds);
  5.         UIWidget widget = GetComponent<UIWidget>();
  6.         widget.height = (int)bounds.extents.y * 2 + 20;
  7.     }

Then of course the panel grows and grows. I could use a bool to do it once of course, but then perhaps the update order can be incorrect?

Is there a simple way to do this?


ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: Correct way to size widget to content
« Reply #1 on: October 29, 2013, 01:29:35 AM »
Nested relative anchors are not a good idea. Instead of doing that, consider using a common ancestor instead, so that all your widgets are anchored / stretched relative to it instead of each other.