LoginSignup
6
6

More than 3 years have passed since last update.

[Swift 5]キーボードを閉じるボタン(画像)をキーボード上部に追加する

Last updated at Posted at 2017-05-29

概要

TextView等の入力欄がキーボードに重なってしまう等で閉じるボタンが欲しいさい、画像(アイコン)で表示できたら余分なスペースを取られなくて済むと思い実装しました。

実装コード例

ViewController.swift
   @IBOutlet weak var textView: UITextView!

   override func viewDidLoad() {
        super.viewDidLoad()

        // 任意の数値
        let buttonWidth: CGFloat = 70
        let buttonHeight: CGFloat = 44
        // ボタンを表示するためのViewを作成
        let keyboardToolView = UIView()
        keyboardToolView.frame.size.height = buttonHeight
        keyboardToolView.backgroundColor = .clear
        // キーボードを閉じるボタンを作成する(画像は任意のものを)
        let closeKeyboardButton = UIButton(
            frame: CGRect(x: UIScreen.main.bounds.size.width - buttonWidth,
                          y: 0,
                          width: buttonWidth,
                          height: buttonHeight
            )
        )
        // 通常時のボタン設定
        closeKeyboardButton.setImage(UIImage(named: "DismissKeyboardButton"), for: .normal)
        // タップした時のアクションを指定
        closeKeyboardButton.addTarget(self, action: #selector(closeKeyboard), for: .touchUpInside)
        // Viewに閉じるButtonを追加する
        keyboardToolView.addSubview(closeKeyboardButton)
        // システムキーボードの上にViewを追加する
        textView.inputAccessoryView = keyboardToolView
    }

UIImage(named: "DismissKeyboardButton") の DismissKeyboardButton を任意の画像名に変えてください。
自分の場合は Assets.xcassets に PDFで入れています。
画像単体で入れている場合は DismissKeyboardButton.png のようになるかと思います。

6
6
0

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
6
6