如何在swift中转换NSValue中的CGPoint?

时间:2014-10-08 07:46:01

标签: ios swift cgpoint nsvalue

正如我的问题标题所说我如何将CGPoint转换为NSValues,以便我可以将其存储到数组中 swift

在Objective-C中,我们可以这样做:

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

但有人能告诉我,我怎么能在swift中做到这一点?

提前致谢。

5 个答案:

答案 0 :(得分:38)

尝试类似的东西:

let point = CGPointMake(9, 9)
var pointObj = NSValue(CGPoint: point)

答案 1 :(得分:11)

正如你想象的那样:

let point = CGPoint(x: 9.0, y: 9.0)
let pointObj = NSValue(CGPoint: point)
let newPoint = pointObj.CGPointValue()

答案 2 :(得分:7)

如果您不打算在Objective-C中使用该阵列,并且可以将其保存为Swift阵列,那么您不需要将该点转换为NSValue,您只需添加直接指向数组:

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]

let valuesArray = pointsArray as [NSValue]

答案 3 :(得分:1)

swift 3

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

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

答案 4 :(得分:1)

swift 4

let point = NSValue.init(cgPoint: mask.position)