【问题标题】:Get the frame of the keyboard dynamically动态获取键盘框架
【发布时间】:2012-08-12 22:17:48
【问题描述】:

是否可以动态获取键盘的框架,实际上是它的高度?因为我有一个UITextView,当键盘的输入法改变时,我想根据键盘框架的高度来调整它的高度。如您所知,不同的输入法可能有不同的键盘框架高度。

【问题讨论】:

    标签: iphone ios keyboard uitextview


    【解决方案1】:

    试试这个:

    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWasShown:)
                                             name:UIKeyboardDidShowNotification
                                           object:nil];
    
    - (void)keyboardWasShown:(NSNotification *)notification
    {
    
    // Get the size of the keyboard.
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
    //Given size may not account for screen rotation
    int height = MIN(keyboardSize.height,keyboardSize.width);
    int width = MAX(keyboardSize.height,keyboardSize.width);
    
    //your other code here..........
    }
    

    Tutorial for more information

    【讨论】:

    • 这在 iOS8 中使用不同高度/类型的键盘时特别有用。到目前为止,只需硬编码 216(纵向)就可以了。谢谢。
    • 对于 swift 用户:使用let keyboardSize = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue().size
    • @LoïsDiQual 谢谢
    • 你应该改用UIKeyboardFrameEndUserInfoKey。我不认为这对UIKeyboardDidShowNotification 很重要,但是如果你把它改成UIKeyboardWillShowNotification 你会得到一些奇怪的错误,因为框架将是之前的状态,而不是之后的状态。
    • 更好的方法是使用可选链接: if let keyboardSize: CGSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as?NSValue)?.cgRectValue.size { print("Keyboard size: (keyboardSize )") }
    【解决方案2】:

    只要按照 Apple 的这个教程,你就会得到你想要的。 Apple Documentation。确定键盘覆盖区域请参考tutorial

    【讨论】:

    • 但是我如何检测到输入法更改动作呢?
    • 如果您是程序员,那么您应该知道在任何给定时间您打开了哪个输入软键盘。
    • 我希望我知道,但我不能。如果您知道如何检测输入法更改动作并获取当前键盘的高度,请告诉我。我真的很感激:)
    • 获取输入字符是textField:shouldChangeCharactersInRange。我在输入美元金额时使用它,我不希望使用除小数以外的任何东西
    • 您应该提供一些代码作为示例,因为链接失效的那一天,答案就没有用了。
    【解决方案3】:

    对于 Swift 3 用户,@Hector 代码(有一些补充)将是:

    在您的viewDidLoad 中添加观察者:

    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(_:)), name: .UIKeyboardDidShow , object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHide(_:)), name: .UIKeyboardDidHide , object: nil)
    

    然后实现这些方法:

    func keyboardDidShow(_ notification: NSNotification) {
         print("Keyboard will show!")
         // print(notification.userInfo)
    
         let keyboardSize:CGSize = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue.size
         print("Keyboard size: \(keyboardSize)")  
    
         let height = min(keyboardSize.height, keyboardSize.width)
         let width = max(keyboardSize.height, keyboardSize.width)
    
    }
    
    func keyboardDidHide(_ notification: NSNotification) {
            print("Keyboard will hide!")
    }
    

    【讨论】:

      【解决方案4】:

      您可以将此代码添加到包含 Swift 3 中的文本字段的视图中。这将使文本字段随着键盘上下动画。

      private var keyboardIsVisible = false
      private var keyboardHeight: CGFloat = 0.0
      
      // MARK: Notifications
      
      private func registerForKeyboardNotifications() {
          NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
          NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
      }
      private func deregisterFromKeyboardNotifications() {
          NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
          NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
      }
      
      // MARK: Triggered Functions
      
      @objc private func keyboardWillShow(notification: NSNotification) {
          keyboardIsVisible = true
          guard let userInfo = notification.userInfo else {
              return
          }
          if let keyboardHeight = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.height {
              self.keyboardHeight = keyboardHeight
          }
          if !textField.isHidden {
              if let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber,
                  let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber {
                  animateHUDWith(duration: duration.doubleValue,
                                 curve: UIViewAnimationCurve(rawValue: curve.intValue) ?? UIViewAnimationCurve.easeInOut,
                                 toLocation: calculateTextFieldCenter())
              }
          }
      }
      
      @objc private func keyboardWillBeHidden(notification: NSNotification) {
          keyboardIsVisible = false
          if !self.isHidden {
              guard let userInfo = notification.userInfo else {
                  return
              }
              if let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber,
                  let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber {
                  animateHUDWith(duration: duration.doubleValue,
                                 curve: UIViewAnimationCurve(rawValue: curve.intValue) ?? UIViewAnimationCurve.easeInOut,
                                 toLocation: calculateTextFieldCenter())
              }
          }
      }
      
      // MARK: - Helpers
      
      private func animateHUDWith(duration: Double, curve: UIViewAnimationCurve, toLocation location: CGPoint) {
          UIView.beginAnimations(nil, context: nil)
          UIView.setAnimationDuration(TimeInterval(duration))
          UIView.setAnimationCurve(curve)
          textField.center = location
          UIView.commitAnimations()
      }
      
      private func calculateTextFieldCenter() -> CGPoint {
          if !keyboardIsVisible {
              return self.center
          } else {
              let yLocation = (self.view.frame.height - keyboardHeight) / 2
              return CGPoint(x: self.center.x, y: yLocation)
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-22
        • 1970-01-01
        • 2016-12-05
        • 1970-01-01
        • 1970-01-01
        • 2011-03-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多