键盘隐藏的错误移动视图

时间:2018-08-24 11:29:33

标签: swift

我的问题如下:

  1. 我有以下观点:Initial view。如您所见,此刻用户点击文本区域时,它将被键盘覆盖。因此,我实施了在其他问题中发布的此解决方案。

    var moved = false
    .....
    override func viewWillAppear(_ animated: Bool) {
       super.viewWillAppear(animated)
    
       NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)),
                                           name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    
       NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide),
                                           name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    
    @objc func keyboardWillHide() {
       self.view.frame.origin.y = 0
       moved = false
    }
    
    @objc func keyboardWillChange(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        if self.textField.isFirstResponder {
            if !moved {
                self.view.frame.origin.y = -keyboardSize.height
                moved = true
            }
        } else if self.textArea.isFirstResponder {
            if !moved {
                self.view.frame.origin.y = -keyboardSize.height
                moved = true
            }
        }
    }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
       super.viewWillDisappear(animated)
    
       NotificationCenter.default.removeObserver(self,
                                              name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
       NotificationCenter.default.removeObserver(self,
                                              name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    
  2. 当我轻按文本this happens时,如您所见,我看不到我在文本区域顶部写的内容。

  3. 如果现在我点击文本字段,然后再次点击文本区域this is how it behaves Ant,它正是我在第一步中想要的。

这就是我组织the view

的方式

0 个答案:

没有答案