Swift表视图(聊天UI)如果显示键盘,整个视图越来越低

时间:2018-06-18 16:46:05

标签: ios swift

我尝试创建聊天UI。因此,我在下面添加了一个Tableview和一个文本字段。如果用户想要输入文本字段,整个视图应该会上升,这样可以正常工作。如果用户结束键入并且键盘应该被隐藏,则第一次视图移动一点点,第二次移动时间也降低。它看起来像以下屏幕截图:

使用以下代码:

   override func viewDidLoad() {

    super.viewDidLoad()
    self.myChat.separatorStyle = .none
    getChatId()
    myChat.allowsSelection = false;


    newMessage.delegate = self
    // Do any additional setup after loading the view.

    NotificationCenter.default.addObserver(self, selector: #selector(ChatViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(ChatViewController.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-1
        }
    }
}[![normally it should look like this][1]][1]

the third time i try to tipe in the textfield is completely invisible and at the top is a black bar

问候

1 个答案:

答案 0 :(得分:2)

更改此功能。

@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
    }
}

}