Jigs Sheth
Jigs Sheth

Reputation: 51

Cannot Convert the expression's type 'CGRect' to type to 'NSCopying!' in swift

Cannot Convert the expression's type 'CGRect' to type to 'NSCopying!' in swift I am trying to implement Keyboard notification in swift file.

// Called when the UIKeyboardDidShowNotification is sent.

  func keyboardWasShown(aNotification :NSNotification)
    {
        var info = aNotification.userInfo
        var kRect:CGRect = info[UIKeyboardFrameBeginUserInfoKey] as CGRect
        var kbSize:CGSize = kRect.size

but not sure why am I getting this error?

Upvotes: 4

Views: 1937

Answers (2)

skymook
skymook

Reputation: 3676

You now need to unwrap userInfo, and it is best to put it in an if statement because it can also be nil

func keyboardWasShown(aNotification: NSNotification) {
    if let info = aNotification.userInfo {
        var keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue()
        // do something with keyboardFrame

    }
}

Upvotes: 3

Mick MacCallum
Mick MacCallum

Reputation: 130193

You can't downcast the value you're pulling out of the dictionary to CGRect. It's an NSValue object, so you can easily get the rect value out of it with CGRectValue(). This should get you what you want.

func keyboardWasShown(aNotification: NSNotification) {
    let info = aNotification.userInfo

    if let rectValue = info[UIKeyboardFrameBeginUserInfoKey] as? NSValue {
        let kbSize:CGSize = rectValue.CGRectValue().size
    }
}

Upvotes: 6

Related Questions