LoginSignup
0
1

More than 3 years have passed since last update.

キーボードが出現するタイミングでTextFieldをずらすコードの書き方[Xcode/Storyboard]

Posted at

Xcode/Storyboardで、キーボード出現時にTextFieldが隠れないようにずらす方法をアウトプットします。

Unknown.gif

環境

・Mac Book Pro(macOS:BigSur)
・Xcode(ver:12.5)

コード

ViewController.swift
  class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var button: UIButton!

    var screenSize = UIScreen.main.bounds.size

    override func viewDidLoad() {

        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_ :)), name:UIResponder.keyboardWillShowNotification, object: nil)

        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    @objc func keyboardWillShow(_ notification:NSNotification){

        let keyboardHeight = ((notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as Any)as AnyObject).cgRectValue?.height

        textField.frame.origin.y = screenSize.height - keyboardHeight! - textField.frame.size.height

        button.frame.origin.y = screenSize.height - keyboardHeight! - button.frame.size.height
    }

    @objc func keyboardWillHide(_ notification:NSNotification){

        textField.frame.origin.y = screenSize.height - textField.frame.size.height

        button.frame.origin.y = screenSize.height - button.frame.size.height
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        textField.resignFirstResponder()
    }
}

解説

「var screenSize = UIScreen.main.bounds.size」は、画面の大きさを指しています。
「 NotificationCenter.default.addObserver」を使って、キーボードが出てくるタイミングや隠れるタイミングを監視します。
「keyboardWillShowNotification」は、キーボード出現時、
「keyboardWillHideNotification」は、キーボードが隠れる場合を監視するときに使います。
上記のタイミングが訪れたときに、selectorで設定したメソッドが呼ばれます。
上記のコードの場合だと、「keyboardWillShow」・「keyboardWillHide」になります。
キーボードが出てくるときに、TextFieldを上にあげる処理が必要になります。
それが、「keyboardWillShow」の中身の処理になります。
今回の場合だと、TextFieldとButtonのy座標を画面の高さからキーボードと各パーツの高さを引きます。
逆にキーボードが下に下がるときに、元に戻す処理が必要になります。
それが、「keyboardWillHide」の中身の処理になります。
画面の高さから各パーツの高さを引くことで下の位置に下がります。

以上となります。

0
1
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
0
1