How to write this code quickly?

I have this code written in 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]; } 

Now, I want to write this code in swift. This is what I have so far:

 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) 

this line is incorrect:

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

What is wrong with this line?

This is a compiler error:

"Could not find an overload for" init "that takes the supplied arguments."

+5
source share
1 answer

A call like Swift fails because the font you add to the dictionary is optional. NSFont(name:size:) returns optional NSFont? , and you need a deployed version. To protect the code, you need something like this:

 // get the font you want, or the label font if that 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] 
+5
source

Source: https://habr.com/ru/post/1204651/


All Articles