Reputation: 1341
I'm attempting to create a chat interface for iOS that expands and shrinks according to the presence of the keyboard.
I have implemented it using observers for the keyboard will show and will disappear notifications and its working.
func keyboardWillDisappear(notification: NSNotification){
var userInfo:NSDictionary = notification.userInfo!
var keyboardSize = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey)!.CGRectValue().size
var oldViewFrame : CGRect = self.view.frame
self.view.frame = CGRectMake (0, 0, oldViewFrame.width, oldViewFrame.height + keyboardSize.height)
}
func keyboardWillAppear(notification: NSNotification){
var keyboardSize = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey)!.CGRectValue().size
var oldViewFrame : CGRect = self.view.frame
self.view.frame = CGRectMake (0, 0, oldViewFrame.width, oldViewFrame.height - keyboardSize.height)
}
Now to some extent this works however if the user attempts to activate or deactivate predictive typing suggestions the thing blows up. keyboardWillAppear gets called but keyboardWillDisappear doesn't and so the view shrinks again and again every time predictions are enabled
There must be simpler and safer way in doing this, and if there are other things I should watch out for please tell me. Thanks
Upvotes: 0
Views: 83
Reputation: 1341
func keyboardFrameWillChange(notification : NSNotification){
var userInfo:NSDictionary = notification.userInfo!
var oldKeyboardHeight : CGSize = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue().size
var newKeyboardHeight : CGSize = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey)!.CGRectValue().size
var oldViewFrame : CGRect = self.view.frame
var difference = newKeyboardHeight.height - oldKeyboardHeight.height
self.view.frame = CGRectMake (0, 0, oldViewFrame.width, oldViewFrame.height - difference)
scrollToBottom()
}
This is the piece of code that used to fix my problem.
Upvotes: 0
Reputation: 61
You need to also observe
UIKeyboardWillChangeFrameNotification
and/or
UIKeyboardDidChangeFrameNotification
Upvotes: 1