How to get a value from NSValue in Swift?

不问归期 提交于 2020-01-03 11:02:02

问题


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}}.


回答1:


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


来源:https://stackoverflow.com/questions/25091765/how-to-get-a-value-from-nsvalue-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!