【Swift】TextViewのキーボードに"閉じる(Done)"ボタンを追加
完成図
解説
UITextFieldはDelegateメソッドでキーボードを閉じられる。
だが、UITextViewには明確な方法がない。
touchesBegan内でresignFirstResponderを実行しても閉じられない始末。
そこで、キーボード内にキーボードを閉じる機能を搭載したボタンを追加する。
従来の方法と比べて少々手間だが、UI/UX的にもユーザーにわかりやすいのでおすすめ。
UIToolBarでキーボードの上部にツールバーを設置
↓
.barStyleでスタイルを設定
↓
.sizeToFitで自動的にサイズを調整
↓
UIBarButtonItemで閉じるボタンの左に設置するスペース(空白)を生成
↓
UIBarButtonItemで閉じるボタンを生成
↓
.itemsでtoolBarに上記の2つ(BarButtonItem)を格納
↓
.inputAccessoryViewでツールバーをセット
ソースコード
import UIKit class addCloseButton: UIViewController,UITextFieldDelegate { @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() // ツールバー生成 let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 320, height: 40)) // スタイルを設定 toolBar.barStyle = UIBarStyle.default // 画面幅に合わせてサイズを変更 toolBar.sizeToFit() // 閉じるボタンを右に配置するためのスペース? let spacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil) // 閉じるボタン let commitButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(addCloseButton.commitButtonTapped)) // スペース、閉じるボタンを右側に配置 toolBar.items = [spacer, commitButton] // textViewのキーボードにツールバーを設定 textView.inputAccessoryView = toolBar } @objc func commitButtonTapped() { self.view.endEditing(true) } }