キーボードが開いたタイミングで送信用のViewを表示し、キーボードのちょうど上の位置に配置というようなことをやりたいです。
viewはxibで作成し、viewdidloadのタイミングでaddsubviewし、コード上で制約を付けておきます。
キーボードが出てきたタイミングでキーボードの高さを取得、viewのbottomの制約をキーボードの高さ分だけ上に上げるという流れで処理しようと思っています。
以下コードになりますが、このやり方だとViewが上がってくるものの微妙にずれていて、デバイスによっては大きなズレが生じます。
swift
1class CompanyDetailViewController: UIViewController { 2 3 var applyView: ApplyView! 4 private var applyViewBottom: NSLayoutConstraint? 5 6 override func viewDidLoad() { 7 super.viewDidLoad() 8 // ここでViewを作成し、初期のAutoLayoutを付けています。 9 self.applyView = UINib(nibName: "ApplyView", bundle: nil).instantiate(withOwner: self, options: nil)[0] as! ApplyView 10 view.addSubview(self.applyView) 11 self.applyView.translatesAutoresizingMaskIntoConstraints = false 12 self.applyView.heightAnchor.constraint(equalToConstant: 204) 13 self.applyView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true 14 self.applyView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true 15 let applyViewBotttom = self.applyView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0) 16 applyViewBotttom.isActive = true 17 self.applyViewBottom = applyViewBotttom 18 addNotification() 19 } 20 21 override func didReceiveMemoryWarning() { 22 super.didReceiveMemoryWarning() 23 NotificationCenter.default.removeObserver(self) 24 } 25 26 private func addNotification() { 27 NotificationCenter.default.addObserver(self, 28 selector: #selector(keyboardWillShowNotification(notification:)), 29 name: .UIKeyboardWillShow, 30 object: nil) 31 NotificationCenter.default.addObserver(self, 32 selector: #selector(keyboardWillHideNotification(notification:)), 33 name: NSNotification.Name.UIKeyboardWillHide, 34 object: nil) 35 } 36 37 @objc func keyboardWillShowNotification(notification: NSNotification) { 38 guard let userInfo = notification.userInfo as? [String: Any] else { 39 return 40 } 41 guard let keyboardInfo = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue else { 42 return 43 } 44 guard let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double else { 45 return 46 } 47 // ここでキーボードの高さを取得、viewのbottomconstraintを変更しています。 48 self.applyView.isHidden = false 49 self.applyViewBottom?.constant = -keyboardInfo.cgSizeValue.height 50 UIView.animate(withDuration: duration) { 51 self.view.layoutIfNeeded() 52 } 53 } 54 55 @objc func keyboardWillHideNotification(notification: NSNotification) { 56 guard let userInfo = notification.userInfo as? [String: Any] else { 57 return 58 } 59 guard let keyboardInfo = userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue else { 60 return 61 } 62 } 63}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/05/25 03:58
2018/05/25 03:58