2014-10-14 15 views
5

mam ten kod napisany w Objective C:Jak napisać ten kod w szybkim tempie?

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]; 
} 

Teraz chcę napisać ten kod SWIFT. To, co mam do tej pory:

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) 

ta linia jest źle:

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

Co jest złego w tym wierszu?

Jest to błąd z kompilatora:

„Nie można znaleźć przeciążenie dla«init», który akceptuje dostarczonych argumentów”.

+1

Co jest nie tak z tą linią? Xcode powinien pokazać ci jakiś błąd. –

+0

Nie można znaleźć przeciążenia dla "init", który akceptuje podane argumenty. To jest błąd. Próbowałem użyć mniej atrybutów, ale otrzymałem ten sam błąd. –

Odpowiedz

5

Wnioskowanie typu Swift zawodzi, ponieważ czcionka dodawana do słownika jest opcjonalna. NSFont(name:size:) zwraca opcjonalny NSFont?, a potrzebujesz wersji nieopakowanej. Aby kodować defensywnie, będziesz potrzebować czegoś takiego:

// 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] 
+0

To jest niesamowite! Dziękuję Ci bardzo –

Powiązane problemy