관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] 키보드에 return을 done 버튼으로 변경 방법 (+ didEndOnExit 이벤트) 본문

iOS 응용 (swift)

[iOS - swift] 키보드에 return을 done 버튼으로 변경 방법 (+ didEndOnExit 이벤트)

jake-kim 2021. 5. 20. 23:18

done버튼 설정

  • done버튼이 아닌 경우, 디폴트는 return

  • Return Key를 Default에서 Done으로 변경

return or done 이벤트 처리

  • @IBAction에서 "Did End On Exit"으로 처리: 해당 @IBAction이 연결되는 순간, return키나 done키가 눌리면 keyboard가 resignFirstResponder되는 기능도 자동으로 처리
    • 주의:editingDidEnd은 다른 텍스트 필드로 포커스가 이동될때도 호출

  • didEndOnExit의 @IBAction을 연결하면 Done 또는 return키를 누를 때 keyboard가 사라지는 기능이 자동으로 추가
    • 해당 @IBAction을 연결하지 않으면 done버튼을 눌러도 keyboard가 사라지지 않는점을 주의

 

Keyboard 위 Toolbar를 통한 Done버튼 추가 방법

  • 해당 방법의 단점
    • 불필요한 UIToolbar영역 존재: iPhone SE와 같이 작은 단말기에서 toolbar와 함께 키보드 자체가 차지하는 영역이 과한 점
    • didEndOnExit이벤트가 아닌 editingDidEnd델리게이트를 사용하여 처리해야 하는점

  • Extension으로 추가 후 사용
extension UITextField{

    @IBInspectable var doneAccessory: Bool{
        get{
            return self.doneAccessory
        }
        set (hasDone) {
            if hasDone{
                addDoneButtonOnKeyboard()
            }
        }
    }

    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: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))

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

        inputAccessoryView = doneToolbar
    }

    @objc func doneButtonAction() {
        endEditing(true)
    }

}
  • xib에서 선택하여 사용

* UIToolbar를 통해 done 버튼 만드는 방법 참고: https://medium.com/swift2go/swift-add-keyboard-done-button-using-uitoolbar-c2bea50a12c7

Comments