2016-07-12 46 views
2

我創建了一個聊天界面,並且像WhatsApp一樣,我創建了一個「scrollToBottom」按鈕,當用戶滾動某個距離的集合時出現。這個按鈕在鍵盤出現時完全遵循鍵盤框架,當鍵盤出現時消失,唯一的問題是當交互式鍵盤被解除時,我不能使該按鈕跟隨鍵盤框架。只有在隱藏鍵盤後,系統纔會發送通知,並且按鈕會更改其常量。獲取鍵盤高度,同時被滾動交互地解僱

我試過所有的鍵盤通知,沒有人幫我解決這個問題。我需要及時需要的東西,這使得按鈕不受任何延遲地按下鍵盤。即使UIKeyboardWillChangeFrameNotification還沒有爲我工作。

NSNotificationCenter.defaultCenter().addObserver(self, 
                 selector:#selector(self.keyboardWillShow(_:)), 
                 name:UIKeyboardWillShowNotification, 
                 object:nil) 
NSNotificationCenter.defaultCenter().addObserver(self, 
                 selector:#selector(self.keyboardWillHide(_:)), 
                 name:UIKeyboardWillHideNotification, 
                 object:nil) 

private func configureConstantViewNewMessages(notification: NSNotification){ 
     if let userInfo = notification.userInfo { 
      let animationDuration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue 
      let keyboardEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() 
      let convertedKeyboardEndFrame = view.convertRect(keyboardEndFrame, fromView: view.window) 
      let rawAnimationCurve = (notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).unsignedIntValue << 16 
      let animationCurve = UIViewAnimationOptions(rawValue: UInt(rawAnimationCurve)) 

      self.kNewMessages.constant = CGRectGetMaxY(view.bounds) - CGRectGetMinY(convertedKeyboardEndFrame) + 10 

      UIView.animateWithDuration(animationDuration, delay: 0.0, options: [.BeginFromCurrentState, animationCurve], animations: { 
       self.view.layoutIfNeeded() 
       }, completion: nil) 
     } 
    } 

通過上面的代碼中,我調用該方法configureConstantViewNewMessages動畫我的按鈕(kNewMessages)的常數,它可根據鍵盤高度改變其位置。

感謝您的支持,並對英語錯誤表示歉意。

+0

內.animateWithDuration塊,把你的按鈕的框架鍵盤解除(例如,如果你想在底部,它會像button.frame.size.height = scrollView.contentSize.height)。或者,您可以通過一個約束實現這一點,該約束將保存該按鈕,並且每次鍵盤顯示或解除時修改該約束的值(仍在animateWithDuration中並調用layoutIfNeeded())。 – Cristian

+1

我已經在使用它,使用第二個選項,我使用與底部相關的按鈕約束,並在每次鍵盤框架更改時修改其值。但是當我滾動我的收藏視圖時,我的問題與關閉鍵盤有關。當用戶交互式地解除它時,我想使按鈕跟隨鍵盤的框架。我不知道我解釋的方式是否有點奇怪。 –

回答

1

請使用下面的代碼可能適合你。

override func viewWillAppear(animated: Bool) { 
      NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) 
} 



func keyboardWillShow(notification:NSNotification) { 
     let userInfo:NSDictionary = notification.userInfo! 
     let keyboardFrame:NSValue = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue 
     let keyboardRectangle = keyboardFrame.CGRectValue() 
     let keyboardHeight = keyboardRectangle.height 
     print(keyboardHeight) 
    } 
1

當鍵盤消失時,添加觀察者以獲取鍵盤位置的通知。

此通知將爲您提供包含有關鍵盤的寬度和高度信息用戶信息

要被放置在結束時,你應該使用這個文件link