React native detect IOS status bar height when cal

2020-03-25 11:31发布

问题:

Status bar height changes when calling or sharing personal hotspot on ios and overlaps view, how to detect status bar height when it changes?

回答1:

I've faced this challenge and haven't found answers on stackoverflow / github issues.

I've come up with my own solution, and post it so this can save some time for others.

import { NativeModules, StatusBarIOS } from 'react-native'
const { StatusBarManager } = NativeModules

componentDidMount () {
  if (Platform.OS === 'ios') {
    StatusBarManager.getHeight(response =>
        this.setState({statusBarHeight: response.height})
    )

    this.listener = StatusBarIOS.addListener('statusBarFrameWillChange',
      (statusBarData) =>
        this.setState({statusBarHeight: statusBarData.frame.height})
    )
  }
}

componentWillUnmount () {
  if (Platform.OS === 'ios' && this.listener) {
    this.listener.remove()
  }
}

How it works

1) get initial height, note it's async method

StatusBarManager.getHeight(response =>
    this.setState({statusBarHeight: response.height}))

2) setup listener for status bar change

StatusBarIOS.addListener('statusBarFrameWillChange',
    (statusBarData) =>
      this.setState({statusBarHeight: statusBarData.frame.height})
  )

3) remove listener in componentWillUnmount

if (Platform.OS === 'ios' && this.listener) {
  this.listener.remove()
}


回答2:

You can use react-native-status-bar-height library to get height of status bar, and can use like

marginTop: getStatusBarHeight()

or you can use as a height of StatusBar, if its set to translucent.

If you are using Expo

then just import { Constants } from 'expo'

and height will be Constants.statusBarHeight

See Ref Here and here for Expo



回答3:

Now it's import Constants from 'expo-constants';

Change 'expo' to 'expo-constants'.