Author Topic: Anchor to Top/Left, ignore Right/Bottom  (Read 2520 times)

UndercoverDesigns

  • Newbie
  • *
  • Thank You
  • -Given: 2
  • -Receive: 0
  • Posts: 7
    • View Profile
Anchor to Top/Left, ignore Right/Bottom
« on: June 14, 2014, 02:26:15 PM »
I'm creating some player buttons dynamically, and have that part down pat.  I've got a UISprite object that will host the buttons created.

I want the first button to align to 20px of the left and -20 px of the top of the ButtonHost object, but I want the button to keep it's width and height, so not anchor to the right/bottom of the parent.

Then, if this is a subsequent button, it needs to align to the previous one (which works correctly).

My code is:

  1. if (Players.Count == 0) {
  2.         // We have to set the anchor to the listGridRoot
  3.         PlayerButtonSprite.SetAnchor(ButtonHost, 20, 20, -20, -20);
  4. } else {
  5.         // we have to set the anchor to the previous player button
  6.         GameObject PreviousPlayerButton = Players [Players.Count - 1].Button;
  7.  
  8.         PlayerButtonSprite.SetAnchor(PreviousPlayerButton, 0, -50, 0, -50);
  9. }

As a follow-on, how would I expand the ButtonHost item to surround all of the created buttons?


ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: Anchor to Top/Left, ignore Right/Bottom
« Reply #1 on: June 15, 2014, 05:42:31 AM »
This code will anchor only the top and left sides, leaving right and bottom sides not anchored:
  1. PlayerButtonSprite.leftAnchor.target = PreviousPlayerButton;
  2. PlayerButtonSprite.leftAnchor.Set(0f, 20f); // 0 = left side, +20 pixels
  3.  
  4. PlayerButtonSprite.topAnchor.target = PreviousPlayerButton;
  5. PlayerButtonSprite.topAnchor.Set(1f, -20f); // 1 = top side, -20 pixels
  6.  
  7. // Re-calculate the widget's anchors using the current values
  8. PlayerButtonSprite.ResetAnchors();
  9. PlayerButtonSprite.UpdateAnchors();
...however you mentioned that you want to keep the width and height. And the only way to keep them is to anchor all 4 sides. Anchor left to left, right to left, top to top, bottom to top.
  1. // Save desired width and height
  2. int width = PlayerButtonSprite.width;
  3. int height = PlayerButtonSprite.height;
  4.  
  5. // Anchor left to left
  6. PlayerButtonSprite.leftAnchor.target = PreviousPlayerButton;
  7. PlayerButtonSprite.leftAnchor.Set(0f, 20f);
  8.  
  9. // Anchor right to left
  10. PlayerButtonSprite.rightAnchor.target = PreviousPlayerButton;
  11. PlayerButtonSprite.rightAnchor.Set(0f, 20f + width);
  12.  
  13. // Anchor top to top
  14. PlayerButtonSprite.topAnchor.target = PreviousPlayerButton;
  15. PlayerButtonSprite.topAnchor.Set(1f, -20f);
  16.  
  17. // Anchor bottom to top
  18. PlayerButtonSprite.bottomAnchor.target = PreviousPlayerButton;
  19. PlayerButtonSprite.bottomAnchor.Set(1f, -20f + height);