How to convert CGPoint in NSValue in swift?

2019-01-19 10:44发布

As my question title says how can I convert CGPoint into NSValues so I can store then Into array In swift.

In objective-C we can do it like this:

  // CGPoint converted to NSValue
     CGPoint point = CGPointMake(9, 9);
     NSValue *pointObj = [NSValue valueWithCGPoint:point];

But can anybody tell me that how can I do this in swift?

Thanks In Advance.

5条回答
劳资没心,怎么记你
2楼-- · 2019-01-19 10:53

Try something like that:

let point = CGPointMake(9, 9)
var pointObj = NSValue(CGPoint: point)
查看更多
我命由我不由天
3楼-- · 2019-01-19 10:54

If you aren't planning on using the array in Objective-C, and can keep it as a Swift Array, then you don't need to turn the point into an NSValue, you can just add the point to the array directly:

let point1 = CGPoint(x: 9.0, y: 9.0)
let point2 = CGPoint(x: 10.0, y: 10.0)

let pointArray = [point1, point2] // pointArray is inferred to be of type [CGPoint]
查看更多
别忘想泡老子
4楼-- · 2019-01-19 10:58

Exactly as you'd imagine:

let point = CGPoint(x: 9.0, y: 9.0)
let pointObj = NSValue(CGPoint: point)
let newPoint = pointObj.CGPointValue()
查看更多
Root(大扎)
5楼-- · 2019-01-19 11:06

swift 4

let point = NSValue.init(cgPoint: mask.position)
查看更多
SAY GOODBYE
6楼-- · 2019-01-19 11:11

swift 3

let pointObj =  NSValue(cgPoint: CGPoint(x:9, y:9))

https://developer.apple.com/reference/foundation/nsvalue/1624531-init

查看更多
登录 后发表回答