Author Topic: scrollView: best practice to indicate whether scrollView at top/bottom now?  (Read 1932 times)

maxtangli

  • Newbie
  • *
  • Thank You
  • -Given: 2
  • -Receive: 0
  • Posts: 4
    • View Profile
Hi, everyone.
I have to made a upScrollable/downScrollable indicator sprite.
Each time scrollView dragged or gameObjects added/removed, below is desired:

bool upScrollable = ?
bool bottomScrollable = ?
upScrollableSprite.enabled = upScrollable
bottomScrollableSprite.enabled = bottomScrollable

The quesion is how to get upScrollable/bottomScrollable ?

I tried two ways, both have defects:
1. use UIScrollBar
bool upScrollable = scrollBar.value > threshold
but threshold may varies for gameObjects count.

2. calculate with scroll.panel/ scroll.bounds.size.y / scroll.panel.GetViewSize() things.
It works, but too complex.

   public void setGameObjects(IEnumerable<GameObject> gameObjects) {
      scroll.ResetPosition();
      // clear existed
      // set new
      grid.Reposition();
      scroll.ResetPosition();

      yWhenTop = scroll.panel.clipOffset.y;
      StartCoroutine("delayedUpdateButtonVisibility");
   }

   // scroll.bounds.size seems won't update until next frame
   IEnumerator delayedUpdateButtonVisibility() {
      yield return new WaitForEndOfFrame();
      updateButtonVisibility();
   }

   float yWhenTop;
   public void updateButtonVisibility() {
      Debug.Log("updateButtonVisibility()");
      if (scroll.bounds.size.y <= scroll.panel.GetViewSize().y) { // contents less than one screen
         buttonPrev.gameObject.SetActive(false);
         buttonNext.gameObject.SetActive(false);
      } else {
         float yWhenBottom = yWhenTop - (scroll.bounds.size.y - scroll.panel.GetViewSize().y);
         buttonPrev.gameObject.SetActive(scroll.panel.clipOffset.y < yWhenTop);
         buttonNext.gameObject.SetActive(scroll.panel.clipOffset.y > yWhenBottom);
      }
   }

So what would the best practice be to indicate whether scrollView at top/bottom now?

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
The math for all this can be found inside the UIScrollView.UpdateScrollbars function. It calculates the bounds of the content and compares them against the bounds of the scroll view, which sounds like what you want to do as well. I suggest having a look inside it.

Also note that calling UpdateScrollbars(true) will force-update the bounds right away. You mentioned you have to wait a frame -- if you call this function, you won't have to.

maxtangli

  • Newbie
  • *
  • Thank You
  • -Given: 2
  • -Receive: 0
  • Posts: 4
    • View Profile
Thanks very much for your reply :).