LoginSignup
5

More than 5 years have passed since last update.

【Swift4】キーボードに追従するツールバーを実装する

Last updated at Posted at 2018-03-17

実行環境

【Xcode】Version 9.2
【Swift】Version 4.0.3

やりたいこと

キーボードの動きに合わせて動くツールバーをUIScrollViewを使わずに実装する。

Untitled3.gif

下準備

まず、Text FieldUIViewstoryboardに配置します。

Text Field → 今回は適当。
UIView → left,right,bottomを0、heightを50にしてます。

この時のUIViewがツールバーになります。

1.png

次に、UIViewbottomconstantIBOutletにします。

2.png

この制約をキーボードの表示と非表示に合わせて変化させることによって、ツールバーがキーボードについてくるように見せます。

実装

   @IBOutlet weak var toolbar: UIView!
    @IBOutlet weak var toolbarBottomConstant: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()

        //キーボードが現れるときに通知するメソッドを登録
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillBeShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

        //キーボードが閉じるときに通知するメソッドを登録
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillBeHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    //キーボードが開くときの呼び出し
    @objc func keyboardWillBeShown(notification: NSNotification) {

        if let userInfo = notification.userInfo {
            if let keyboardFrameInfo = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {

                //ツールバーの最大Y座標と、キーボードの最小Y座標の差を計算
                let diff = self.toolbar.frame.maxY -  keyboardFrameInfo.cgRectValue.minY

                if (diff > 0) {
                    //ツールバーのbottomの制約に差分をプラス
                    self.toolbarBottomConstant.constant += diff

                    //レイアウトを更新
                    self.view.layoutIfNeeded()
                }
            }
        }

    }

    //キーボードが閉じるときの呼び出し
    @objc func keyboardWillBeHide(notification: NSNotification) {
        //ツールバーのbottomの制約を元に戻す
        self.toolbarBottomConstant.constant = 0.0

        //レイアウトを更新
        self.view.layoutIfNeeded()
    }

    //テキストフィールド以外をタッチしたとき
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //キーボードを閉じる
        self.view.endEditing(true)
    }

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
5