How to get a value from NSValue in Swift?
Asked Answered
P

1

7

Here's what I've tried so far

func onKeyboardRaise(notification: NSNotification) {
    var notificationData = notification.userInfo
    var duration = notificationData[UIKeyboardAnimationDurationUserInfoKey] as NSNumber
    var frame = notificationData[UIKeyboardFrameBeginUserInfoKey]! as NSValue
    var frameValue :UnsafePointer<(CGRect)> = nil;
    frame.getValue(frameValue)
}

But I always seem to crash at frame.getValue(frameValue).

It's a little bit confusing because the documentation for UIKeyboardFrameBeginUserInfoKey says it returns a CGRect object, but when I log frame in the console, it states something like NSRect {{x, y}, {w, h}}.

Pete answered 2/8, 2014 at 4:47 Comment(1)
It is not an unsafe pointer so don't turn it into one! Just read the docs on NSValue: developer.apple.com/library/ios/documentation/uikit/reference/… This is no different from doing it in Objective-C. No need to make easy things hard for yourself.Touchhole
S
10

getValue() must be called with a pointer to an (initialized) variable of the appropriate size:

var frameValue = CGRect(x: 0, y: 0, width: 0, height: 0)
frame.getValue(&frameValue)

But it is simpler to use the convenience method:

let frameValue = frame.CGRectValue() // Swift 1, 2
let frameValue = frame.cgRectValue() // Swift 3
Seafaring answered 2/8, 2014 at 4:54 Comment(1)
This is awesome, thank you sir! I had trouble in the beginning because xCode doesn't autocomplete if you start typing "CGRec.." so I thought the method didn't exist. Another bug in xCode beta!Pete

© 2022 - 2024 — McMap. All rights reserved.