ScrollView弹跳的2种不同背景颜色

时间:2016-11-01 18:13:46

标签: react-native react-native-ios

我有ScrollView,其顶部有一种背景颜色,底部有另一种颜色。

当用户滚动浏览内容并且视图反弹(弹性过度延伸)时,我怎样才能使背景与顶部或底部一致,具体取决于滚动方向?

3 个答案:

答案 0 :(得分:6)

在iOS上,您可以在View之上呈现间隔ScrollView,并使用contentInset将其呈现为“屏幕外”,contentOffset以设置初始滚动位置以抵消插入:

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>
  );
}

由于contentInsetcontentOffset 仅限iOS ,因此此示例的条件是在Android上正常降级。

答案 1 :(得分:5)

我不会使用ScrollView的contentInsetcontentOffset,就好像您的内容更改了一样,它可能会更改滚动视图的位置。

您可以通过在ScrollView的最顶部添加一个View来做非常简单的事情:

// const spacerSize = 1000;

<ScrollView>
  {Platform.OS === 'ios' && (
    <View 
      style={{
        backgroundColor: 'red',
        height: spacerSize,
        position: 'absolute',
        top: -spacerSize,
        left: 0,
        right: 0,
      }} 
    />
  }
</ScrollView>

答案 2 :(得分:1)

被接受的解决方案对我来说效果不佳,因为我需要在contentContainerStyle上放置IConfidentialClientApplication WithClientSecret()。使用插入/偏移不会使内容按我想要的方式增长,否则效果还不错。

我有另一个建议的解决方案:在透明ScrollView下放置一个双色背景层,并为您的scrollview内容添加颜色。这样,在ios反弹时,滚动视图下的双色层将显示出来。

这就是我所说的双色层(这里的滚动视图是空的和透明的)

enter image description here

现在,如果我放回ScrollView子级(如果该子级具有空白背景,而页脚具有黄色背景),则会得到以下信息:

enter image description here

只要弹跳不超过滚动视图高度的50%,您就会看到适当的背景颜色。

这是您可以用来包装滚动视图的组件。

flexGrow: 1

这是您的用法:

const AppScrollViewIOSBounceColorsWrapper = ({
  topBounceColor,
  bottomBounceColor,
  children,
  ...props
}) => {
  return (
    <View {...props} style={[{ position: 'relative' }, props.style]}>
      {children}
      <View
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          width: '100%',
          height: '100%',
          zIndex: -1, // appear under the scrollview
        }}
      >
        <View
          style={{ flex: 1, backgroundColor: topBounceColor }}
        />
        <View
          style={{ flex: 1, backgroundColor: bottomBounceColor }}
        />
      </View>
    </View>
  );
};

确保不要在滚动视图中设置背景色,否则双色层将永远不会显示出来(contentContainerStyle上的backgroundColor很好)

相关问题