Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find keyboard height using Swift

let frame = (info[UIKeyboardFrameEndUserInfoKey] as NSValue) as CGRect

does not work. Anybody know why this does not function as expected?

Error: 'NSValue' not convertible to 'CGRect'

Keep in mind that something like:

let curve = (info[UIKeyboardAnimationCurveUserInfoKey] as NSValue) as UInt

works fine.

Edit: Even Apple documentation indicates this is a glitch because of the following comment in Cocoa for UIKeyboardAnimationCurveUserInfoKey

// NSValue of CGRect

Edit2: The debugger defines it as an NSConcreteValue. How can I convert it to a CGRect?

like image 363
CaptainCOOLGUY Avatar asked Aug 07 '14 00:08

CaptainCOOLGUY


2 Answers

let frame = (info[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue()
like image 187
Alexey Globchastyy Avatar answered Nov 15 '22 04:11

Alexey Globchastyy


To use keyboardFrame height with NSNotificationCenter

override func viewWillAppear(animated: Bool) {


        NSNotificationCenter.defaultCenter().addObserver(self,
                                                         selector: #selector(self.keyboardWasShown(_:)),
                                                         name: UIKeyboardWillChangeFrameNotification,
                                                         object: nil)

        NSNotificationCenter.defaultCenter().addObserver(self,
                                                         selector: #selector(self.keyboardWillHide(_:)),
                                                         name: UIKeyboardWillHideNotification,
                                                         object: nil)


    }



    func keyboardWasShown(notification: NSNotification) {
        let info = notification.userInfo!
        let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()

        UIView.animateWithDuration(0.1, animations: { () -> Void in
            self.constBottomLayout.constant = keyboardFrame.size.height
        })
    }


    func keyboardWillHide(sender: NSNotification) {
        // self.view.frame.origin.y = 0
        self.constBottomLayout.constant = 0
    }
like image 24
Nischal Hada Avatar answered Nov 15 '22 03:11

Nischal Hada