我想将MKMapPoint转换为NSValue。在Objective-C中,我可以使用以下语句来完成:
MKMapPoint point = MKMapPointForCoordinate(location.coordinate);
NSValue *pointValue = [NSValue value:&point withObjCType:@encode(MKMapPoint)];
我怎样才能在Swift中做到这一点? 谢谢!
答案 0 :(得分:2)
在Swift中不可能,但您仍然可以在ObjC中创建一个类别并在Swift项目中使用它
// NSValue+MKMapPoint.h
@interface NSValue (MKMapPoint)
+ (NSValue *)valueWithMKMapPoint:(MKMapPoint)mapPoint;
- (MKMapPoint)MKMapPointValue;
@end
// NSValue+MKMapPoint.m
@implementation NSValue (MKMapPoint)
+ (NSValue *)valueWithMKMapPoint:(MKMapPoint)mapPoint {
return [NSValue value:&mapPoint withObjCType:@encode(MKMapPoint)];
}
- (MKMapPoint)MKMapPointValue {
MKMapPoint mapPoint;
[self getValue:&mapPoint];
return mapPoint;
}
@end
Swift中的用法:
let mapValue = CGValue(MKMapPoint: <your map point>)
let mapPoint = mapValue.MKMapPointValue();
答案 1 :(得分:1)
我认为狮子座的答案不再正确, 我设法通过下面的代码将MKMapPoint数组转换为CGPoint数组:
let polygonView = MKPolygonRenderer(overlay: overlay)
let polyPoints = polygonView.polygon.points() //returns [MKMapPoint]
var arrOfCGPoints : [CGPoint] = []
for i in 0..<polygonView.polygon.pointCount {
arrOfCGPoints.append(polygonView.point(for: polyPoints[i])) //converts to CGPoint
}
print(arrOfCGPoints)
//prints [(10896.74671715498, 10527.267575368285), (10830.46552553773, 10503.901612073183), (10741.784851640463, 10480.270403653383), (10653.04738676548, 10456.62348484993), (10566.442882657051, 10409.803505435586)]
然后转到NSValue:
ler someCgPoint = arrOfCGPoints[0]
var pointObj = NSValue(CGPoint: someCgPoint)
答案 2 :(得分:0)
可悲的是,这在Swift中是不可能的。
答案 3 :(得分:0)
试试这个
let mapPoint = MKMapPointForCoordinate(coordinate)
let type = NSValue(MKCoordinate: coordinate).objCType // <- THIS IS IT
let value = NSValue(bytes: unsafeAddressOf(mapPoint as! AnyObject), objCType: type);