LoginSignup
13
7

More than 5 years have passed since last update.

swiftで閉じるボタンのついたキーボードを表示するUITextFieldクラスの作成

Last updated at Posted at 2018-01-01

背景

キーボードって閉じるボタンがデフォルトではついていないから不便だな〜と思って、閉じるボタンのついたクラスを作成しました。2ステップで導入できるので気軽に利用できます。是非使ってみてください。

目次

  1. 環境
  2. 手順① クラスファイルの作成
  3. 手順②(最後) StoryBoardに反映
  4. 参考文献

開発環境

バージョン
Swift: 3.2
Xcode: 8.3.3
Swift4でも動くと思います。確かめてはいないので、もし試した方がいたら教えてくださると嬉しいです。

手順① クラスファイルの作成

New -> File より新しいSwiftファイルを作成し、以下のようなコードを追記してください。 

KeyBoard.swift
import Foundation
import UIKit


//閉じるボタンの付いたキーボード
class DoneTextFierd: 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(self.closeButtonTapped))
        tools.items = [spacer, closeButton]
        self.inputAccessoryView = tools
    }

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

手順②(最後) StoryBoardに反映

今回はStoryBoardを利用しましたけど、コードのでの実装もすぐできると思います。
UITextFieldのクラスにKeyBoardと書くだけでおっけーです。これ実行するとUITextFieldを開いた時に完了ボタンが現れ、実際に閉じる動作まで動きます。

参考文献

覚えている範囲ですが、閉じるボタンの追加の時に閲覧した記事をこちらで紹介させていただきます。
UITextViewのkeyboardに完了ボタンを追加してkeyboardを閉じる方法

13
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
7