I read the docs that talk about this topic . I transferred it to Swift, and it worked great for me.
This is used for a full UITextView page, such as iMessage.
I am using iOS 8.2 and Swift on Xcode 6.2, and here is my code. Just call setupKeyboardNotifications from your viewDidLoad or other initialization method.
func setupKeyboardNotifications() { NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWasShown:"), name: UIKeyboardDidShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillBeHidden:"), name: UIKeyboardWillHideNotification, object: nil) } func keyboardWasShown(aNotification:NSNotification) { let info = aNotification.userInfo let infoNSValue = info![UIKeyboardFrameBeginUserInfoKey] as NSValue let kbSize = infoNSValue.CGRectValue().size let contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0) codeTextView.contentInset = contentInsets codeTextView.scrollIndicatorInsets = contentInsets } func keyboardWillBeHidden(aNotification:NSNotification) { let contentInsets = UIEdgeInsetsZero codeTextView.contentInset = contentInsets codeTextView.scrollIndicatorInsets = contentInsets }
Also, if you have problems with the carriage being in the right place when it is rotated, check the orientation change and scroll to the desired position.
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { scrollToCaretInTextView(codeTextView, animated: true) } func scrollToCaretInTextView(textView:UITextView, animated:Bool) { var rect = textView.caretRectForPosition(textView.selectedTextRange?.end) rect.size.height += textView.textContainerInset.bottom textView.scrollRectToVisible(rect, animated: animated) }
Swift 3:
func configureKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(aNotification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(aNotification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func keyboardWasShown(aNotification:NSNotification) { let info = aNotification.userInfo let infoNSValue = info![UIKeyboardFrameBeginUserInfoKey] as! NSValue let kbSize = infoNSValue.cgRectValue.size let contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0) textView.contentInset = contentInsets textView.scrollIndicatorInsets = contentInsets } func keyboardWillBeHidden(aNotification:NSNotification) { let contentInsets = UIEdgeInsets.zero textView.contentInset = contentInsets textView.scrollIndicatorInsets = contentInsets }
Johnston Mar 30 '15 at 12:47 2015-03-30 12:47
source share