Get the frame of the keyboard dynamically

旧时模样 提交于 2020-01-09 13:11:42

问题


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 keyboard frame height, when the input method of the keyboard is changed. As you know, different input methods may have different keyboard frame height.


回答1:


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




回答2:


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.




回答3:


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!")
}



回答4:


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


来源:https://stackoverflow.com/questions/11989306/get-the-frame-of-the-keyboard-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!