본문 바로가기

iOS

[iOS] 키보드 툴바 만들기

728x90

안드로이드는 키보드를 내려주는 버튼이 있지만, iOS에서는 없으므로,

UITextView 나 UITextField 등 텍스트 입력 후 키보드를 닫아주는 처리가 필요하다.

 

전체 배경에 버튼이나 탭 제스쳐를 입혀서 키보드를 내려주는 액션을 추가해도 되지만, 

현재 개발중인 기능과 비슷한 기능(메모)에 키보드 툴바 - [완료] 버튼으로 키보드를 내려주고 있었다.

Objective-C로 되어있는 코드라, Swift 코드로 만들고 적용한 것을 정리해본다.

 

AS-IS / TO-BE

 

 

private func createKeyboardToolbar() -> UIToolbar {
        let toolBarKeyboard = UIToolbar()
        
        toolBarKeyboard.sizeToFit()
        
        let editDoneButton = UIBarButtonItem(title: R.string.zipdoc.done(), style: .done, target: self, action: #selector(self.doneEditTextView))
        
        toolBarKeyboard.items = [editDoneButton]
        
        // 버튼 텍스트 컬러
        toolBarKeyboard.tintColor = .carrot
        
        // 툴바 배경 컬러
        toolBarKeyboard.barTintColor = .concrete
        
        return toolBarKeyboard
    }
    
    /// keyboard toolbar [완료] 버튼 액션
    /// 입력 완료 버튼 액션
    @objc func doneEditTextView() {
        self.view.endEditing(true)
    }

위의 코드로 키보드 툴바를 만들고, 이걸 UITextView나 UITextField의 inputAccessoryView로 셋팅해준다.

아래와 같이!

        // textview accessory view
        // 키보드 툴바 셋팅
        self.inputTextView.inputAccessoryView = self.createKeyboardToolbar()

 

요렇게 버튼을 오른쪽으로 위치하게끔 하고 싶은 경우, toolbar의 item으로 flexible space 속성의 버튼을 만들어서 넣어주면 된다.

 

        // [완료] 버튼을 오른쪽으로 위치하기 위한 공백 추가
        let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
        
        let editDoneButton = UIBarButtonItem(title: R.string.zipdoc.done(), style: .done, target: self, action: #selector(self.doneEditTextView))
        
        toolBarKeyboard.items = [space, editDoneButton]

 

728x90