Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 Different Background Colours For ScrollView bounce

I have a ScrollView that has a top section with one background colour and a bottom section with another different colour.

When a user scrolls past the content and the view bounces (elastic over-extend), how could I make it so the background is consistent with either the top or the bottom, depending on the scroll direction?

like image 906
Alex Curtis Avatar asked Nov 01 '16 18:11

Alex Curtis


2 Answers

I wouldn't play with the contentInset and contentOffset of the ScrollView as if your content changes, it might change the position of your scrollview.

You can do something very simple by just adding a View at the very top of your ScrollView:

// const spacerHeight = 1000;

<ScrollView>
  {Platform.OS === 'ios' && (
    <View 
      style={{
        backgroundColor: 'red',
        height: spacerHeight,
        position: 'absolute',
        top: -spacerHeight,
        left: 0,
        right: 0,
      }} 
    />
  )}
</ScrollView>
like image 176
alexmngn Avatar answered Oct 31 '22 03:10

alexmngn


On iOS, you can render a spacer View on top of the ScrollView, and use contentInset to render it "off-screen", contentOffset to set the initial scroll position to offset the inset:

render() {
  const isIos = Platform.OS === 'ios'
  const SPACER_SIZE = 1000; //arbitrary size
  const TOP_COLOR = 'white';
  const BOTTOM_COLOR = 'papayawhip';
  return (
    <ScrollView
      style={{backgroundColor: isIos ? BOTTOM_COLOR : TOP_COLOR }}
      contentContainerStyle={{backgroundColor: TOP_COLOR}}
      contentInset={{top: -SPACER_SIZE}}
      contentOffset={{y: SPACER_SIZE}}>

      {isIos && <View style={{height: SPACER_SIZE}} />}
      //...your content here

    </ScrollView>
  );
}

Because contentInset and contentOffset are iOS only, this example is conditioned to degrade gracefully on Android.

like image 14
jevakallio Avatar answered Oct 31 '22 02:10

jevakallio