如何在swift中编写这段代码?

时间:2014-10-14 14:24:22

标签: objective-c macos swift

我有这个用Objective c编写的代码:

NSRect textRect = NSMakeRect(42, 35, 117, 55);
{
    NSString* textContent = @"Hello, World!";
    NSMutableParagraphStyle* textStyle = NSMutableParagraphStyle.defaultParagraphStyle.mutableCopy;
    textStyle.alignment = NSCenterTextAlignment;

    NSDictionary* textFontAttributes = @{NSFontAttributeName: [NSFont fontWithName: @"Helvetica" size: 12], NSForegroundColorAttributeName: NSColor.blackColor, NSParagraphStyleAttributeName: textStyle};

    [textContent drawInRect: NSOffsetRect(textRect, 0, 1 - (NSHeight(textRect) - NSHeight([textContent boundingRectWithSize: textRect.size options: NSStringDrawingUsesLineFragmentOrigin attributes: textFontAttributes])) / 2) withAttributes: textFontAttributes];
}

现在,我想在swift中编写这段代码。这是我迄今为止所得到的:

let textRect = NSMakeRect(42, 35, 117, 55)
let textTextContent = NSString(string: "Hello, World!")
let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as NSMutableParagraphStyle
textStyle.alignment = NSTextAlignment.CenterTextAlignment

let textFontAttributes = [NSFontAttributeName: NSFont(name: "Helvetica", size: 12), NSForegroundColorAttributeName: NSColor.blackColor(), NSParagraphStyleAttributeName: textStyle]

textTextContent.drawInRect(NSOffsetRect(textRect, 0, 1 - (NSHeight(textRect) - NSHeight(textTextContent.boundingRectWithSize(textRect.size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textFontAttributes))) / 2), withAttributes: textFontAttributes)

这条线错了:

   let textFontAttributes = [NSFontAttributeName: NSFont(name: "Helvetica", size: 12), NSForegroundColorAttributeName: NSColor.blackColor(), NSParagraphStyleAttributeName: textStyle]

该行有什么问题?

这是编译器的错误:

  

"无法找到接受所提供参数的“init”的重载"。

1 个答案:

答案 0 :(得分:5)

Swift的类型推断使您失败,因为您添加到字典中的字体是可选的。 NSFont(name:size:)返回一个可选的NSFont?,您需要一个展开的版本。要进行防御性编码,你需要这样的东西:

// get the font you want, or the label font if that's not available
let font = NSFont(name: "Helvetica", size: 12) ?? NSFont.labelFontOfSize(12)

// now this should work
let textFontAttributes = [NSFontAttributeName: font, NSForegroundColorAttributeName: NSColor.blackColor(), NSParagraphStyleAttributeName: textStyle]