如何用Swift编写这段代码?

5

我有一段用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
那行代码有什么问题?Xcode 应该会显示一些错误信息。 - Sebastian Wramba
找不到接受提供的参数的“init”重载。这是错误。我尝试使用较少的属性,但仍收到相同的错误。 - C-Viorel
1个回答

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]

太棒了!非常感谢你。 - C-Viorel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接