...

반응형

 

Text View나 Text Field에서 키보드를 열고 닫을때 다른 곳을 클릭하거나 드래그로 닫을 수도 있지만

좀 더 직관적으로 사진 처럼 닫기 버튼을 만들 수 있습니다

 

func addDoneButtonOnKeyboard(){
        let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
        doneToolbar.barStyle = .default

        let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let done: UIBarButtonItem = UIBarButtonItem(title:  NSLocalizedString("keyboard_close", comment: ""), style: .done, target: self, action: #selector(self.doneButtonAction))

        let items = [flexSpace, done]
        doneToolbar.items = items
        doneToolbar.sizeToFit()

        tvContent.inputAccessoryView = doneToolbar
}

@objc func doneButtonAction(){
        tvContent.resignFirstResponder()
}

 

위 소스의 tvContent를 본인의 textview 나 textfield로 변경 하시면 됩니다

글자는 UIBardButtonItem의 title에서 변경 해주시면 됩니다

doneButtonAction은 닫기 버튼을 눌렀을때 키보드를 내리기 위해 필요합니다

반응형