objective-c - 如何快速编写这段代码?

标签 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]

那一行有什么问题?

这是编译器的错误:

"Could not find an overload for “init” that accepts the supplied arguments".

最佳答案

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]

关于objective-c - 如何快速编写这段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26363268/

相关文章:

macos - NSAlert 高于 NSPopover

Macos Catalina 更新后出现错误 : unable to run colorls

swift - 如何导入fabric-webpack到react-native?

objective-c - 当应用程序隐藏时 NSTimer 停止?

objective-c - 使用 Swift 的 Google map GMSGroundOverlay 委托(delegate)

python - 在 OSX 上为 virtualenv 设置 Python 32 位和 64 位模式

ios - CLLocationManager 未确定位置

php - Alamofire 发布请求失败错误

objective-c - GKSession connectToPeer 方法不会超时

ios - 如何在 CABasicAnimation 中加速/减慢按钮的旋转