当键盘弹出时,我尝试让UITextField和UITextView向上移动。 但是,我发现它只适用于UITextField,但不适用于UITextView。 我错过了什么吗?
textFields和textViews都是委派的。
这是我的代码:
var activeField: UITextField?
var activeView: UITextView?
func registerForKeyboardNotifications()
{
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardWasShown(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardWillBeHidden(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
func deregisterFromKeyboardNotifications()
{
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWasShown(notification: NSNotification)
{
var info : NSDictionary = notification.userInfo!
var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)
self.scrollview.contentInset = contentInsets
self.scrollview.scrollIndicatorInsets = contentInsets
var aRect : CGRect = self.view.frame
aRect.size.height -= keyboardSize!.height
if let activeFieldPresent = activeField
{
if (!CGRectContainsPoint(aRect, activeField!.frame.origin))
{
self.scrollview.scrollRectToVisible(activeField!.frame, animated: true)
}
}
if let activeViewPresent = activeView
{
if (!CGRectContainsPoint(aRect, activeView!.frame.origin))
{
self.scrollview.scrollRectToVisible(activeView!.frame, animated: true)
}
}
}
func keyboardWillBeHidden(notification: NSNotification)
{
var info : NSDictionary = notification.userInfo!
var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
var contentInsets : UIEdgeInsets = UIEdgeInsetsZero
self.scrollview.contentInset = contentInsets
self.scrollview.scrollIndicatorInsets = contentInsets
self.view.endEditing(true)
}
func textFieldDidBeginEditing(textField: UITextField)
{
activeField = textField
registerForKeyboardNotifications()
}
func textFieldDidEndEditing(textField: UITextField)
{
deregisterFromKeyboardNotifications()
activeField = nil
}
func textViewDidBeginEditing(textView: UITextView) {
activeView = textView
registerForKeyboardNotifications()
}
func textViewDidEndEditing(textView: UITextView) {
deregisterFromKeyboardNotifications()
activeView = nil
}