LoginSignup
8
9

More than 5 years have passed since last update.

UIKeyboardDidShowNotificationでtextFieldをキーボードの高さの分だけ移動させる方法

Last updated at Posted at 2016-06-28

LINEのようなチャットアプリでありがちな、画面下部にテキストの入力欄を設けて、そこをタップするとキーボードがせり上がってきてもそれに合わせてテキストの入力欄の位置も移動させる機能を実装したい。

いろいろ試行錯誤してみたのですが、次の3ステップがシンプルかもしれません。

StoryBoardでUIViewControllerの上に、UITableViewとUITextFieldなどを配置する

UITableViewをUIViewControllerの上部に、UITextFieldとその背景のUIView、送信ボタンのUIButtonを合わせてUIViewControllerの下部に配置。

AutoLayoutを当てて、UIViewはサイズを375*40で固定。UITableViewを可変にします。
UIViewController.png

viewDidLoadにNSNotificationCenterを記述

UITableView、UITextField、UIView、UIButtonをソースコードにOutlet接続した上で、viewDidLoadに下記を記述します。

ViewController.swift
    override func viewDidLoad() {
      //省略

      // NSNotificationでキーボードを開けたイベントを取得
      let notificationCenter = NSNotificationCenter.defaultCenter()
      notificationCenter.addObserver(self, selector: #selector(self.openKeyboard(_:)), name: UIKeyboardDidShowNotification, object: nil)
    }

UIKeyboardDidShowNotificationで、キーボードを表示し終えたことの通知が可能です。

キーボードを開いたときに行う処理を記述

通知センターから受け取ったuserInfoを元に、そのユーザーが開いているキーボードのサイズを取得し、そのキーボードの高さの分だけself.textField.frameなどを上に移動させます。

ViewController.swift
    //キーボードを開いたときに入力フィールドを移動させる
    func openKeyboard(notification: NSNotification) {
        if let userInfo = notification.userInfo {
            if let keyboard = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue{
                let keyBoardRect = keyboard.CGRectValue()

                self.textField.frame = CGRectMake(5, (self.view.frame.height - 28 - keyBoardRect.size.height), self.view.frame.width - 70, 28)
                self.sendView.frame = CGRectMake(0, (self.view.frame.height - 40 - keyBoardRect.size.height), self.view.frame.width, 40)
                self.sendButton.frame = CGRectMake(self.view.frame.width - 55, (self.view.frame.height - 28 - keyBoardRect.size.height), 50, 28)

            }
        }
    }

これにより、iPhoneを縦向きにしていても横向きにしていても、キーボードの高さの分だけ、テキスト入力欄の高さを上げることができます。

keyboard-height.png

8
9
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
8
9