I am attempting to change the contentInsets
property of a UITextView
upon they keyboard showing, so that it is not hidden behind the keyboard. I have looked at a number of questions concerning this task, and have tried following the approved or highly voted answers, and have tried following Apple's recommended approach:
My code is currently as follows, in ViewDidLoad():
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
the function that is indicated by the selector is:
func keyboardWillShow(notification : NSNotification){
let info :NSDictionary = notification.userInfo! as NSDictionary;
if let keyboardRect = info.objectForKey(UIKeyboardFrameEndUserInfoKey){
var inset = commentsText.contentInset;
inset.bottom = keyboardRect.size.height
UIView.animateWithDuration(0.25, animations: {
self.commentsText.contentInset = inset
})
}
}
commentsText
is the name of the UITextView
I am trying to adjust the innocence of.
The problem I am having is that when attempting to access keyboardRect.size.heigh
I have a fatal error of attempting to unwrap an unexpected nil value. I really am not sure how to fix this, because as far as I can tell I am following accepted answers and documentation (The animation block is an addition to Apple's documentation, but it is from an accepted answer, How do I resize views when keyboard pops up using Auto Layout , so I figure it probably isn't the source of the problem.
I have also attempted using the UIKeyboardDidShowNotification
as well as using the UIKeyboardFrameBeginUserInfoKey
, but neither of those substitutions changed the error.
The documentation from Apple and most questions/answers on this topic are in Objective-C, and while I think I correctly "translated" them into Swift for my purposes, it is entirely possible I made a mistake somewhere, if this is the case please let me know what my error was.
Any help/suggestions would be appreciated.
Thanks in advance.
P.S. I am currently working in Xcode 7 Beta 6