How to know the useful height of an iOS device in React Native?

戏子无情 提交于 2020-06-25 02:59:10

问题


In some very specific cases I need to set the height of a View to the full height of the device useful area (without using flex).

I was using a hardcoded "notch height" to calculate this useful height but I just discovered that the notch can have different heights depending on the device. (3 points of difference between iPhone XS and iPhone XS Max).

Is there a way to know the useful height of a device with notch and safe area?


回答1:


You can use the react-native-safe-area. it provides function to Get safe area inset top, bottom, left, right.

import SafeArea, { type SafeAreaInsets } from 'react-native-safe-area'

//Retrieve safe area insets for root view

SafeArea.getSafeAreaInsetsForRootView()
.then((result) => {
   console.log(result)
   // { safeAreaInsets: { top: 44, left: 0, bottom: 34, right: 0 } }
})



回答2:


As @mohammed-ashfaq said, react-native-safe-area solves the problem. However, it returns the insets with a promise and I needed those values statically.

Given that, I created react-native-static-safe-area-insets that enables access to the insets values as constants.




回答3:


You can get the screen, which users phone, width and height from Dimensions component.

import { Dimensions } from 'react-native'

const { width, height } = Dimensions.get('window'); // if you use the width you can get the screen width by pixels. And also height is the height pixels of the phone. 

const screenWidthSomePart = width * 0,6 // Some times you can get the percentage of the screen so you can use this. screen %60

If you wanna see the safe are for the Iphone X. You can use the SafeAreaView Componenet

import { SafeAreaView } from 'react-native'
 return(
 <SafeAreaView>
   ..... // your screen componenet
 </SafeAreaView>
); 



回答4:


Use Dimension module from 'react-native' like there :

import { Dimensions, Platform, StatusBar } from 'react-native'

const windowHeight = Dimensions.get('window').height
const screenHeight = Dimensions.get('screen').height


来源:https://stackoverflow.com/questions/53319968/how-to-know-the-useful-height-of-an-ios-device-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!