flyingbirdのiPhoneアプリ開発記録

- PolyRhythmの中の人がiPhoneアプリ開発中に思ったことを記録するブログです -

【Swift】UIToolbarをキーボードと一緒に上げ下げしたい

画面の下に張り付いているUIToolbar… こいつを画面下から現れるキーボードと一緒に上げ下げしたい!!

  • ようやく答えを見つけた。以下のリンクを参照してなんとか解決。

stackoverflow.com

  • リンク先はconstraintsの参照をViewControllerにもたせていたが、identifier使って取ってみた
	@objc private func keyboardWillShow(_ notification: Notification) {
		let frame = notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
		let height = frame.cgRectValue.height
		let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double

		UIView.animate(withDuration: duration) {
			super.view.constraints.first(where: { (constraint) -> Bool in
				return constraint.identifier == "toolBar"
			})!.constant = height
			super.view.layoutIfNeeded()
		}
	}

	@objc private func keyboardWillHide(_ notification: Notification) {
		let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double

		UIView.animate(withDuration: duration) { 
			super.view.constraints.first(where: { (constraint) -> Bool in
				return constraint.identifier == "toolBar"
			})!.constant = 0
			super.view.layoutIfNeeded()
		}
	}