Frontend/React-Native

[React Native] 입력창-키보드 겹치는 문제 - ios

w00se 2021. 4. 27. 00:50

채팅, 댓글 기능이 들어간 앱에서는 일반적으로 아래와 같이

정보들은 위쪽에 입력창이 아래쪽에 배치되어 있는 화면을 갖게 됩니다.

이번 게시글에는 React-Native에서 위와 같은 스크린을 작업할 때 겪었던 'TextInput이 포커스 됐을 때 Keyboard가 올라오며 겹쳐지는 문제'에 대한 ios에서의 해결 방법을 적으려 합니다.

 

문제 상황

TextInput이 포커스 됐을 때 Keyboard가 올라오며 겹쳐진다.

 

 

해결 방안

KeyboardAvoidingView + 적절한 padding 값 조절

 

KeyboardAvoidingView는 React Native 공식 문서에서 지원하는 컴포넌트입니다.

해당 컴포넌트에 대한 공식 문서의 설명은 아래와 같습니다.

It is a component to solve the common problem of views that need to move out of the way of the virtual keyboard.

 

해당 컴포넌트는 가상 키보드에 뷰가 가려지는 문제를 해결하기 위해 사용되며 현재 우리가 직면한 문제에 적용하기 적절한 컴포넌트입니다.

 

위 컴포넌트를 iPhone 12와 iPhon 8에 적용한 결과 화면은 아래와 같습니다.

 

해당 컴포넌트를 적용한 것만으로 적용 전 가려졌던 텍스트 입력창이 키보드 위로 올라온 모습을 확인 가능합니다.

컴포넌트를 적용한 코드는 아래와 같습니다.

 

코드 - KeyboardAvoidingView 적용

import React from 'react'
import { StyleSheet, KeyboardAvoidingView, View, TextInput, Text, Platform, Button, Keyboard } from 'react-native'

const CommentScreen = (props) => {
    const hideKeyboard = () => {
        Keyboard.dismiss()
    }

    return(
        <KeyboardAvoidingView
            style={styles.rootContainer}
            behavior={"padding"}
        >   
            <Button
                title={"키보드 내리기"}
                onPress={hideKeyboard}
            />
            <View style={styles.commentArea}>
                <Text>이곳은 댓글이 보여질 공간 입니다.</Text>
            </View>
            <View style={styles.textInputContainer}>
                <TextInput
                    style={styles.textInput}
                    placeholder="댓글을 입력해주세요"
                    autoCorrect={false}
                />
            </View>
        </KeyboardAvoidingView>
    )
}

const styles = StyleSheet.create({
    rootContainer: {
        flex: 1,
        backgroundColor: "#ffffff"
    },
    commentArea: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: "#ababab"
    },
    textInputContainer: {
        marginTop: "auto",
        borderWidth: 1,
        borderColor: "skyblue",
        justifyContent: "center",
        alignItems: "center",
        padding: 15,
    },
    textInput: {
        width: "100%",
        fontSize: 18,
        borderWidth: 1,
        borderColor: "pink"
    }
})

export default CommentScreen

 

KeyboardAvoidingView를 적용하면 이 게시글에서 다루는 문제는 대부분 해결이 되는 거 같습니다.

그러나 간혹 KeyboardAvoidingView 컴포넌트를 적용해도 아래와 같이 입력창 일부분 또는 전체가 keyboard에 가려지는 현상이 발생합니다.

 

 

이런 경우 keyboardAvoidingView 컴포넌트의 keyboardVerticalOffset props를 이용해 텍스트 입력창이 키보드 위로 올라오도록 조절을 하면 됩니다.

 

저의 경우 keyboardVerticalOffset={44+statusBarHeight} 옵션을 사용했습니다.

*statusBarHeight: 저희 앱에서는 ios 기기 별로 필요한 offset 값이 달리 적용돼야 해서 해당 값을 사용했습니다.

 

코드 - KeyboardAvoidingView + padding 적용

*해당 코드는 전체 코드가 아닌 위 문제를 해결하기 위한 핵심 부분만 발췌한 것입니다.

import React, { useEffect, useState } from 'react'
import { StyleSheet, KeyboardAvoidingView, View, TextInput, Text, Platform, Button, Keyboard, NativeModules } from 'react-native'

const { StatusBarManager } = NativeModules

const CommentScreen = (props) => {
    useEffect(()=>{
        Platform.OS == 'ios' ? StatusBarManager.getHeight((statusBarFrameData) => {
            setStatusBarHeight(statusBarFrameData.height)
          }) : null
    }, []);

    const [statusBarHeight, setStatusBarHeight] = useState(0);

    return(
        <KeyboardAvoidingView
            style={styles.rootContainer}
            behavior={"padding"}
            keyboardVerticalOffset={statusBarHeight+44}
        >   
            {...}
        </KeyboardAvoidingView>
    )
}

const styles = StyleSheet.create({
    rootContainer: {
        flex: 1,
        backgroundColor: "#ffffff"
    },
})

export default CommentScreen

 

props를 적용시킨 결과는 아래와 같습니다.

 

 

 

댓글 작성 화면 더 자세한 내용은 아래의 게시글에서 확인 가능 합니다😊

coding-w00se.tistory.com/18


읽어주셔서 감사합니다.

혹시 본 게시글 중 틀린 내용이 있다면 댓글을 통해 알려주세요 :)