キーボードに閉じるボタンを追加(UITextField,UITextView)【Swift】

■はじめに

iOSのアプリを開発していると、UITextField、UITextViewに文字を入力した後にキーボードが閉じられない という問題に直面している人は多いでしょう。 iOSの場合は、キーボードを閉じるためにも実装が必要になります。

ここでは、キーボードの上に「閉じる」ボタンを設定する方法を記載します。

◾️TextFieldのキーボードに閉じるボタンを設定する

UITextFieldをStoryBoardで配置し他場合を前提に方法を記載する。

「CustomTextField.swift」を作成する。 「CustomTextField.swift」には、以下のソースコードを記載する。(丸々コピーペーストでいい)

import UIKit

class CustomTextField: 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(closeButtonTapped))
        tools.items = [spacer, closeButton]
        self.inputAccessoryView = tools
    }

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

その後、StoryBoardのUITextFieldのCustomClassに、今回作成した「CustomTextField.swift」を指定する。 これで、上記を指定したUITextFieldには、キーボードに「閉じる」ボタンが表示される。 ※「CustomTextField.swift」は共通で使用できるため、キーボードに「閉じる」を表示したい各UITextFieldに設定する事ができる。

◾️TextViewのキーボードに閉じるボタンを設定する

UITextViewをStoryBoardで配置し他場合を前提に方法を記載する。

「CustomTextView.swift」を作成する。 「CustomTextView.swift」には、以下のソースコードを記載する。(丸々コピーペーストでいい)

import UIKit

class CustomTextView: UITextView{

    init(frame:CGRect) {
        super.init(frame: frame, textContainer: nil)
        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(closeButtonTapped))
        tools.items = [spacer, closeButton]
        self.inputAccessoryView = tools
    }

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

その後、StoryBoardのUITextViewのCustomClassに、今回作成した「CustomTextView.swift」を指定する。

これで、上記を指定したUITextViewには、キーボードに「閉じる」ボタンが表示される。

※「CustomTextView.swift」は共通で使用できるため、キーボードに「閉じる」を表示したい各UITextViewに設定する事ができる。