react-native IOS鍵盤遮擋如何解決

1.KeyboardAvoidingView

通過react-native 自帶的這個組件可以解決一些常見的問題

優(yōu)點: 即拿即用方便快捷

缺點: 有部分情況解決起來不是很好

2.CocoaPods 安裝 Ios的 ‘IQKeyboardManager’

通過pods 來安裝 ‘IQKeyboardManager’ 來解決全局的的鍵盤彈出事件

安裝方法也很簡單,先安裝CocoaPods

然后進到項目的ios文件夾下建立Podfile,終端執(zhí)行

pod install 

編輯Podfile增加‘IQKeyboardManager’

# Uncomment the next line to define a global platform for your project
platform :ios, '8.0'

target 'App' do
  # Uncomment the next line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!
  pod "IQKeyboardManager"
end

然后終端執(zhí)行

pod install 

搞定后直接重新build項目發(fā)現(xiàn)全局的鍵盤彈出遮擋問題都已經(jīng)解決。

優(yōu)點: 集成一次后幾乎不用考慮鍵盤遮擋問題,也不需要在代碼上做什么

缺點: 對native的依賴比較大,另一個是對全局生效,無法禁止,除非通過修改native代碼來增加方法給js調用才能禁止。

3.新方法 react-native-keyboard-mgr

多虧了網(wǎng)友的努力出現(xiàn)了新的方案,就是將‘IQKeyboardManager’封裝成npm插件,像其他的插件一樣

yarn add react-native-keyboard-mgr
//or
npm install --save react-native-keyboard-mgr

Api

使用API
npm install --save react-native-keyboard-mgr

setEnabled

如果你想在某些場景禁用鍵盤自適應,只需要使用setEnabled(false)就可以了,

如果你想啟用, 只需要使用setEnabled(true)就可以了。

setEnableAutoToolbar

還可以自定義是否開啟自帶的工具條

setShouldShowTextInputPlaceholder,setPlaceholderFont

修改placholder的顯示和隱藏,和字體大小

setShouldResignOnTouchOutside

點擊背景是否收起鍵盤

例子:

import KeyBorardManager from 'react-native-keyboard-mgr';

export default class App extends Component<Props> {
  constructor(props) {
    super(props);
    this.state = { text: 'Useless Placeholder' };
  }

  render() {
    KeyBorardManager.setEnabled(true)
    KeyBorardManager.setEnableAutoToolbar(false)
    KeyBorardManager.setShouldShowTextInputPlaceholder(false)
    KeyBorardManager.setShouldResignOnTouchOutside(false)
    KeyBorardManager.setPlaceholderFont(10)
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
        <Text style={styles.instructions}>To get started, edit App.js</Text>
        <Text style={styles.instructions}>{instructions}</Text>
        <TextInput
          style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
          onChangeText={(text) => this.setState({ text })}
          value={this.state.text}
        />
      </View>
    );
  }
}

優(yōu)點: 綜合了’IQKeyboardManager‘的優(yōu)點,但是更加靈活

缺點: 網(wǎng)友的私人開源項目,不知道有沒有什么坑

相關鏈接

使用CocoaPods管理項目

react-native-keyboard-mgr

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容