【问题标题】:How to write this code in swift?如何快速编写此代码?
【发布时间】:2014-12-09 09:24:35
【问题描述】:

我有这段代码是用 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”的重载”。

【问题讨论】:

  • 那么,那行有什么问题? Xcode 应该会显示一些错误。
  • 找不到接受所提供参数的“init”的重载。这就是错误。我尝试使用较少的属性,但我收到同样的错误。

标签: objective-c macos swift


【解决方案1】:

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]

【讨论】:

  • 太棒了!非常感谢
猜你喜欢
  • 2011-10-14
  • 2017-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多