【Swift5】textFieldのキーボードに閉じるボタンを付ける。

textFieldのキーボードに閉じるボタンを付けたいときがあります。

参考サイト
swiftで閉じるボタンのついたキーボードを表示するUITextFieldクラスの作成 – Qiita

ほぼ劣化コピペです。
元サイトがなくなったら困るので自分用です。
不都合があれは削除します。(-人-)

UITextFieldのカスタムクラスになります。
以下のコードをコードの最後に追記。

// MARK: - キーボードにと閉じるボタンを付ける
//storybordで該当テキストフィールドを選択し、identity Inspectorでclassを DoneTextFierdに切り替える
class DoneTextFierd: UITextField{

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    private func commonInit(){
        let tools = UIToolbar()
        tools.frame = CGRect(x: 0, y: 0, width: frame.width, height: 40)
        let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
        let closeButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.closeButtonTapped))
        tools.items = [spacer, closeButton]
        self.inputAccessoryView = tools
    }

    @objc func closeButtonTapped(){
        self.endEditing(true)
        self.resignFirstResponder()
    }
}

そして適用したいtextFieldのidentity Inspectorでcustom classをDoneTextFierdに変更する。
スクリーンショット 2020-04-10 21.23.40

これでDone付きのキーボードが出るようになります。
スクリーンショット 2020-04-10 21.28.12

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です