React Native適配IPhoneX系列設備之


  SafeAreaView的目的是在一個“安全”的可視區域內渲染內容。具體來說就是因為目前有 iPhone X 這樣的帶有“劉海”的全面屏設備,所以需要避免內容渲染到不可見的“劉海”范圍內。本組件目前僅支持 iOS 設備以及 iOS 11 或更高版本。

  SafeAreaView會自動根據系統的各種導航欄、工具欄等預留出空間來渲染內部內容。更重要的是,它還會考慮到設備屏幕的局限,比如屏幕四周的圓角或是頂部中間不可顯示的“劉海”區域。

      

  實例代碼:

import {
  //
  SafeAreaView
} from 'react-native';
class Main extends React.Component {
  render() {
    return (
      <SafeAreaView style={styles.safeArea}>
        <App />
      </SafeAreaView>
    )
  }
}
const styles = StyleSheet.create({
  // …,
  safeArea: {
    flex: 1,
    backgroundColor: '#ddd'
  }
})

  通常在開發過程中,為了適配IPhonX設備,需要開發者自己來做代碼操作。例如下面是判斷iPhone X的工具類。

import {
    PixelRatio,
    Dimensions,
    Platform
} from 'react-native';

export let screenW = Dimensions.get('window').width;
export let screenH = Dimensions.get('window').height;
// iPhoneX
const X_WIDTH = 375;
const X_HEIGHT = 812;

/**
 * 判斷是否為iphoneX
 * @returns {boolean}
 */
export function isIphoneX() {
    return (
        Platform.OS === 'ios' &&
        ((screenH === X_HEIGHT && screenW === X_WIDTH) ||
            (screenH === X_WIDTH && screenW === X_HEIGHT))
    )
}

/**
 * 根據是否是iPhoneX返回不同的樣式
 * @param iphoneXStyle
 * @param iosStyle
 * @param androidStyle
 * @returns {*}
 */

export function ifIphoneX(iphoneXStyle, iosStyle, androidStyle) {
    if (isIphoneX()) {
        return iphoneXStyle;
    } else if (Platform.OS === 'ios') {
        return iosStyle
    } else {
        if (androidStyle) return androidStyle;
        return iosStyle
    }
}

  在適配前進行相關的判斷,然后使用SafeAreaView進行適配即可。例如:

/**
 * 根據是否是iPhoneX返回不同的樣式
 * @param iphoneXStyle
 * @param iosStyle
 * @param androidStyle
 * @returns {*}
 */
export function ifIphoneX(iphoneXStyle, iosStyle = {}, androidStyle) {
  if (isIphoneX()) {
    return iphoneXStyle;
  } else if (Platform.OS === 'ios') {
    return iosStyle
  } else {
    if (androidStyle) return androidStyle;
    return iosStyle
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM