我想把UIView放在键盘上

时间:2018-05-07 13:15:31

标签: ios swift keyboard

当显示键盘时,我想测量键盘的高度并在其上放置一个视图。 在下面的代码中,视图被引发但它已经偏离。

过程:

  1. 创建视图
  2. 设置约束(isHidden = true)
  3. 获取键盘的高度
  4. 更新约束(isHidden = false)
  5. 代码:

    class CompanyDetailViewController: UIViewController {
        var applyView: ApplyView!
        private var applyViewBottom: NSLayoutConstraint?
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Create view and set constraint
            self.applyView = UINib(nibName: "ApplyView", bundle: nil).instantiate(withOwner: self, options: nil)[0] as! ApplyView
            view.addSubview(self.applyView)
            self.applyView.translatesAutoresizingMaskIntoConstraints = false
            self.applyView.heightAnchor.constraint(equalToConstant: 204)
            self.applyView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
            self.applyView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
            let applyViewBotttom = self.applyView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0)
            applyViewBotttom.isActive = true
            self.applyViewBottom = applyViewBotttom
            addNotification()
        }
    
        private func addNotification() {
            NotificationCenter.default.addObserver(self,
                                                   selector: #selector(keyboardWillShowNotification(notification:)),
                                                   name: .UIKeyboardWillShow,
                                                   object: nil)
        }
    
        @objc func keyboardWillShowNotification(notification: NSNotification) {
            guard let userInfo = notification.userInfo as? [String: Any] else {
                return
            }
            guard let keyboardInfo = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue else {
                return
            }
            guard let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double else {
                return
            }
            // Get keyboard's height and update constraint
            self.applyView.isHidden = false
            self.applyViewBottom?.constant = -keyboardInfo.cgSizeValue.height
            UIView.animate(withDuration: duration) {
                self.view.layoutIfNeeded()
            }
        }
    }
    

1 个答案:

答案 0 :(得分:0)

试试这个

@objc func keyboardWillShowNotification(_ notification: Notification) {

    if let userInfo = notification.userInfo {

        let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue

        let isKeyboardShowing = notification.name == NSNotification.Name.UIKeyboardWillShow

        applyViewBotttom.constant = isKeyboardShowing ? -keyboardFrame!.height : 0

        UIView.animate(withDuration: 0.5, animations: { () -> Void in
            self.view.layoutIfNeeded()
        })
    }

Demo example