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've got until now :
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 wrong :
let textFontAttributes = [NSFontAttributeName: NSFont(name: "Helvetica", size: 12), NSForegroundColorAttributeName: NSColor.blackColor(), NSParagraphStyleAttributeName: textStyle]
What is wrong with that line ?
This is the error from the compiler :
"Could not find an overload for “init” that accepts the supplied arguments".
Swift's type inference is failing you because the font you're adding to the dictionary is an optional. NSFont(name:size:)
returns an optional NSFont?
, and you need an unwrapped version. To code defensively, you'll want something like this:
// 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With