【Swift3】キーボードに閉じるボタン。

UITextfieldやUITextViewでキーボードに閉じるボタンがほしい。

てなわけで参考サイト。
(UITextViewの)キーボードに「閉じる」ボタンを追加する – ながいものには、まかれたくない
iOSでキーボードを閉じる方法各種 – Qiita

ほぼコピペですが、Swift3でちょこっとだけ直されました。

import UIKit

class ViewController: UIViewController, UITextFieldDelegate{
    
    @IBOutlet weak var mainTextView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        makeKeybord()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    func makeKeybord(){
        // 仮のサイズでツールバー生成
        let kbToolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 320, height: 40))
        kbToolBar.barStyle = UIBarStyle.default  // スタイルを設定
        
        kbToolBar.sizeToFit()  // 画面幅に合わせてサイズを変更
        
        // スペーサー
        let spacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil)
        
        // 閉じるボタン
        let commitButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(ViewController.commitButtonTapped))
        
        kbToolBar.items = [spacer, commitButton]
        mainTextView.inputAccessoryView = kbToolBar
    }
    
    func commitButtonTapped (){
        self.view.endEditing(true)
    }
    

よく使いますよね。ヽ(^。^)ノ

コメントを残す

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