iOSでキーボードを表示した時に閉じるボタン(完了)が必要な場面が結構多いので今後の為にメモ。
1行で入力させるTextViewであれば閉じるボタンがキーボード上に表示されますが、改行が必要な場合や2行以上あるTextViewの場合、閉じるボタンを追加した方がユーザーフレンドリーだと思われます。
UITextViewでキーボードに閉じるボタンを追加する方法
import UIKit class ViewController: UIViewController ,UITextViewDelegate{ @IBOutlet weak var textview: UITextView! @objc func onClickCommitButton (sender: UIButton) { if(textview.isFirstResponder){ textview.resignFirstResponder() } } override func viewDidLoad() { super.viewDidLoad() let custombar = UIView(frame: CGRect(x:0, y:0,width:(UIScreen.main.bounds.size.width),height:40)) custombar.backgroundColor = UIColor.groupTableViewBackground let commitBtn = UIButton(frame: CGRect(x:(UIScreen.main.bounds.size.width)-50,y:0,width:50,height:40)) commitBtn.setTitle("閉じる", for: .normal) commitBtn.setTitleColor(UIColor.blue, for:.normal) commitBtn.addTarget(self, action:#selector(ViewController.onClickCommitButton), for: .touchUpInside) custombar.addSubview(commitBtn) textview.inputAccessoryView = custombar textview.keyboardType = .default textview.delegate = self } }
UITextViewにはキーボードにViewを追加できる「inputAccessoryView」があるので、
inputAccessoryViewに閉じるボタンを追加したViewをUITextViewの「inputAccessoryView」に追加してます。
閉じるボタンを押したタイミングでUITextViewの「resignFirstResponder()」でキーボードを閉じるようにしています。
参考: