Author Topic: Adding Items to Grid Programatically  (Read 2791 times)

iPedro

  • Newbie
  • *
  • Thank You
  • -Given: 1
  • -Receive: 0
  • Posts: 2
    • View Profile
Adding Items to Grid Programatically
« on: August 13, 2014, 10:22:25 PM »
I'm adding items to a grid inside a scrollview using the following code.  The problem is the first item in the list appears about 2 items down leaving a blank space at the top of the grid/scrollview...  Any idea why this is happening?

  1. UIGrid grid = GameObject.FindWithTag("GamesGrid").GetComponent<UIGrid>() as UIGrid;
  2.  
  3.                         if(!grid)
  4.                                 Debug.LogError("No Grid Found!");
  5.                         else
  6.                         {
  7.                                 for(int i = 0; i < CGameManager.Instance.mGames.Count; i++)
  8.                                 {
  9.                                         GameObject obj = NGUITools.AddChild(grid.gameObject, mGameButton);
  10.                                         obj.GetComponent<GameListItem>().Game = CGameManager.Instance.mGames[i];
  11.                                        
  12.                                         CGameManager.Instance.mGamesListItems.Add(obj);
  13.                                 }
  14.                         }
  15.  
  16.                         grid.Reposition();

Here's a picture of what I mean...


ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: Adding Items to Grid Programatically
« Reply #1 on: August 14, 2014, 07:41:09 AM »
You need to either reset the scroll view (UIScrollView.ResetPosition) or move your grid so that it begins on top.

Note that UIScrollView.ResetPosition won't work immediately unless you broadcast "CreatePanel" to your newly instantiated widgets first.
  1. grid.Reposition();
  2. grid.gameObject.BroadcastMessage("CreatePanel");
  3. grid.GetComponentInParent<UIScrollView>().ResetPosition();

iPedro

  • Newbie
  • *
  • Thank You
  • -Given: 1
  • -Receive: 0
  • Posts: 2
    • View Profile
Re: Adding Items to Grid Programatically
« Reply #2 on: August 14, 2014, 11:11:22 AM »
Thank you Mr. Mook!!  Saw you talk at GDC 2013 and wanted to say hi.  Hopefully will run into you next year!  Thanks for the quick reply and solution!  :D