指定したTextField がkeyboardで隠れないようにする
iOSで開発する時、TextFieldをタップすると、
TextFieldが出でくるkeyboardに隠される時よくある。
↓このように。
1. こういう時は下のTextField がkeyboardで隠れないように。
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.configureObserver() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.removeObserver() } // Notificationを設定 func configureObserver() { let notification = NotificationCenter.default notification.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) notification.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } // Notificationを削除 func removeObserver() { let notification = NotificationCenter.default notification.removeObserver(self) } // Keyboardが現れた時Viewをずらす。 func keyboardWillShow(notification: Notification?) { //上のTextFieldをタップする時そのまま、下のTextFieldをタップする時Viewをずらす。 if secondTextField.isFirstResponder { let rect = (notification?.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue let duration: TimeInterval? = notification?.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? Double UIView.animate(withDuration: duration!, animations: { () in let transform = CGAffineTransform(translationX: 0, y: -(rect?.size.height)!) self.view.transform = transform }) } } // Keyboardが消えたときViewを戻す func keyboardWillHide(notification: Notification?) { let duration: TimeInterval? = notification?.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? Double UIView.animate(withDuration: duration!, animations: { () in self.view.transform = CGAffineTransform.identity }) }
2. keyboard以外のところでタップするとkeyboardが消える。
まずはViewControllerでTap Gesture Recognizerを追加する。
そして右のReferencing Outlet CollectionのところでViewとつなげる、
最後にViewControllerでviewTappedというActionを追加する。
@IBAction func viewTapped(_ sender: Any) { view.endEditing(true) }
これでkeyboard以外のところでタップするとkeyboardが消える。
3. Return buttonをタップするとkeyboardが消える。
func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true }
これを追加すればおっけです。
完成したDemoの動きは以下です。