Objective-C to Swift:NSScreen

时间:2015-05-16 05:50:57

标签: objective-c xcode swift cocoa

我正在学习斯威夫特。作为测试,我正在将一些旧的Objective-C程序翻译成快速的。但是我有一个疯狂的错误:在Objective-C中我有以下代码:

- (CGSize)makeSizeFromCentimetersWidth: (CGFloat)width andY: (CGFloat)height {

    NSScreen *screen = [NSScreen mainScreen];
    NSDictionary *description = [screen deviceDescription];
    NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue];
    CGSize displayPhysicalSize = CGDisplayScreenSize([[description objectForKey:@"NSScreenNumber"] unsignedIntValue]);

    CGFloat resolution = (displayPixelSize.width / displayPhysicalSize.width) * 25.4f;
    CGFloat pixelsWidth = 0.394 * width * resolution;
    CGFloat pixelsHeight = 0.394 * height * resolution;

    return CGSizeMake(pixelsWidth, pixelsHeight);

}

在swift中,我已经翻译成这个:

func makeSizeFromCentimeters(width: CGFloat, height: CGFloat) -> CGSize {

    var screen: NSScreen = NSScreen.mainScreen()!

    var description: NSDictionary = screen.deviceDescription
    var displayPixelSize: NSSize = description.objectForKey(NSDeviceSize)!.sizeValue
    var displayPhysicalSize: CGSize = CGDisplayScreenSize(description.objectForKey("NSScreenNumber")!.unsignedIntValue)
    var resolution = (displayPixelSize.width / displayPhysicalSize.width) * 25.4

    var pixelsWidth: CGFloat = 0.394 * width * resolution
    var pixelsHeight: CGFloat = 0.394 * height * resolution

    return CGSizeMake(pixelsWidth, pixelsHeight)

}

在Objective-C中,代码完成了它应该做的事情:计算从厘米到像素的大小,给出(在我的情况下)一个NSImageView,其大小与给定的厘米完全相同。但在Swift中,返回的大小始终为0:

NSLog("%f", makeSizeFromCentimeters(2, height: 2).width)
NSLog("%f", makeSizeFromCentimeters(2, height: 2).height)

是否存在翻译错误?哪个变量是0? (不知道为什么它不应该是0,如果它不是由变量引起的。)

感谢您的帮助!

0 个答案:

没有答案