代码之家  ›  专栏  ›  技术社区  ›  rantanplan

KeyboardWillHide方法上的布局不会更新

  •  0
  • rantanplan  · 技术社区  · 8 年前

    我已经能够使用keyboardwillshow方法更新scrollview的布局约束。但是,当尝试在keyboardwillhide方法中执行相同操作时,布局将不会更新(导致滚动视图在键盘用于启动的位置被切断)。关于如何解决这个问题有什么提示吗?谢谢!!

    @objc func keyboardWillShow(notification: NSNotification) {
        let info = notification.userInfo!
        let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        keyboardHeightSubtraction = keyboardFrame.size.height
        scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -keyboardHeightSubtraction).isActive = true
        UIView.animate(withDuration: 0.3, animations: { () -> Void in
            self.view.layoutIfNeeded()
        })
    }
    
    
    @objc func keyboardWillHide(notification: NSNotification) {
        scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        UIView.animate(withDuration: 0.3, animations: { () -> Void in
            self.view.layoutIfNeeded()
        })
    }
    
    3 回复  |  直到 8 年前
        1
  •  2
  •   Shehata Gamal    8 年前

    问题是,您当前在约束中创建冲突,因此请在 viewDidLoad 在这两个函数中它是恒定的\

    var botCon:NSLayoutConstraint!
    

    / /

    botCon = scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
    botcon.isActive = true
    

    / /

    @objc func keyboardWillShow(notification: NSNotification) {
        let info = notification.userInfo!
        let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        botCon.constant = -1 * keyboardHeightSubtraction 
        UIView.animate(withDuration: 0.3, animations: { () -> Void in
            self.view.layoutIfNeeded()
        })
    }
    
    
    @objc func keyboardWillHide(notification: NSNotification) {
        botCon.constant = 0
        UIView.animate(withDuration: 0.3, animations: { () -> Void in
            self.view.layoutIfNeeded()
        })
    }
    
        2
  •  1
  •   ashish    8 年前

    你可以使用 UIEdgeInsects 捕捉键盘的高度并根据您的视图添加一个自定义的填充以从底部分隔滚动视图,然后在键盘关闭时将滚动视图昆虫设置回零。

    var contentPadding: CGFloat = 60


    键盘将出现

    func keyboardWillShow(notification: NSNotification) {
        var userInfo = notification.userInfo!
        var keyboardFrame: CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        keyboardFrame = self.view.convert(keyboardFrame, from: nil)
    
        var contentInset: UIEdgeInsets = self.scrollView.contentInset
        contentInset.bottom = keyboardFrame.size.height + contentPadding // custom padding
        scrollView.contentInset = contentInset
    }
    

    键盘将消失

    func keyboardWillHide(notification: NSNotification) {
        let contentInset: UIEdgeInsets = UIEdgeInsets.zero
        scrollView.contentInset = contentInset
    }