AppSeedのアプリ開発ブログ

アプリ開発会社AppSeed(アップシード)開発担当のブログです。iOS、Android、Unity、Cocos2d-xなどアプリ開発関連のTipsや備忘録、アプリ開発に役立つ情報を発信します。

【iOS】UITextViewでキーボードに閉じる(完了)ボタンを追加する方法(Swift)

【iOS】UITextViewでキーボードに閉じるボタンを追加する方法(Swift)

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()」でキーボードを閉じるようにしています。

参考:

developer.apple.com

developer.apple.com

developer.apple.com