AnyObject To CGPoint

时间:2015-01-14 00:18:14

标签: objective-c swift

我似乎无法解决这个问题,我有一个返回NSArray的Objective-C函数,我知道NSArray中的数据包含CGPoint对象我在世界上如何将它转换为数组

这是函数

+(NSArray *)translatePoints:(NSArray *)points fromView:(UIView *)fromView toView:(UIView *)toView
{
    NSMutableArray *translatedPoints = [NSMutableArray new];

    // The points are provided in a dictionary with keys X and Y
    for (NSDictionary *point in points) {
        // Let's turn them into CGPoints
        CGPoint pointValue = CGPointMake([point[@"X"] floatValue], [point[@"Y"] floatValue]);
        // Now translate from one view to the other
        CGPoint translatedPoint = [fromView convertPoint:pointValue toView:toView];
        // Box them up and add to the array
        [translatedPoints addObject:[NSValue valueWithCGPoint:translatedPoint]];
    }

    return [translatedPoints copy];
}

1 个答案:

答案 0 :(得分:4)

您的translatesPoints方法会返回包含NSArray的{​​{1}} NSValueCGPoint。让我们创建一个这样的数组:

let arr:NSArray = [NSValue(CGPoint: CGPointMake(1,2)), NSValue(CGPoint: CGPointMake(3,4))]

您可以从此数组中获取值并在其上调用CGPointValue()

for val in arr as [NSValue] {
    let point = val.CGPointValue()
    println("CGPoint = (\(point.x), \(point.y))")
}

如果需要,可以将整个NSArray转换为CGPoint的Swift数组,如下所示:

let points = (arr as [NSValue]).map({$0.CGPointValue()})

现在points的类型为[CGPoint]