在swift4

时间:2018-04-19 17:14:53

标签: ios swift uitextfield

我有一般消息视图控制器我正在使用文本字段发送消息但键盘覆盖了文本字段。我可以参考 Move view with keyboard using Swift  这个链接添加了一些代码,但之后一些部分显示黑色。如何在发送消息后避免屏幕变黑

enter image description here

enter image description here

enter image description here

这是代码

   override func viewDidLoad() {
            super.viewDidLoad()
            NotificationCenter.default.addObserver(self, selector: #selector(GenralMessageViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(GenralMessageViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }


   @objc func keyboardWillShow(notification: NSNotification) {
      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0 {
            self.view.frame.origin.y -= keyboardSize.height
           }
        }
    }

   @objc func keyboardWillHide(notification: NSNotification) {
      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
          if self.view.frame.origin.y != 0{
              self.view.frame.origin.y += keyboardSize.height
           }
        }
   }

2 个答案:

答案 0 :(得分:1)

你的代码是错的。您无法更改frame的{​​{1}}。视图控制器的主视图必须保留在原位。将您的界面包裹在主视图的子视图中并移动子视图(如果您坚持使用此方法以避免被键盘覆盖)。

答案 1 :(得分:0)

尝试将结束y原点更改回0而不是计算值。

   @objc func keyboardWillHide(notification: NSNotification) {
      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
          if self.view.frame.origin.y != 0{
              self.view.frame.origin.y == 0
           }
        }
   }