简体   繁体   中英

How should I correctly set contentInset for UITextView when Keyboard appears

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:

https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html#//apple_ref/doc/uid/TP40009542-CH5-SW7

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.

PS I am currently working in Xcode 7 Beta 6

Here's how to get the keyboard rect (a CGRect) out of the NSNotification:

let info = notification.userInfo!
let keyboardRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM