Get the frame of the keyboard dynamically

前端 未结 4 1166
逝去的感伤
逝去的感伤 2020-12-14 00:48

Is it possible to get the frame, actually its height, of the keyboard dynamically? As I have a UITextView and I would like to adjust its height according to the

相关标签:
4条回答
  • 2020-12-14 01:07

    You can add this code to the view which contains the text field in Swift 3. This will make the text field animate up and down with the keyboard.

    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)
        }
    }
    
    0 讨论(0)
  • 2020-12-14 01:08

    For the Swift 3 users, the @Hector code (with some additions) would be:

    In your viewDidLoad add the observer :

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

    Then implement those methods:

    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!")
    }
    
    0 讨论(0)
  • 2020-12-14 01:13

    Just follow this tutorial from Apple and you will get what you want. Apple Documentation. In order to determine the area covered by keyboard please refer to this tutorial.

    0 讨论(0)
  • 2020-12-14 01:16

    try this:

    [[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

    0 讨论(0)
提交回复
热议问题