2014-10-05 174 views
18

Xcode 6.1 GM有一個奇怪的問題。Swift - 使用drawInRect繪製文本:withAttributes:

let text: NSString = "A" 
let font = NSFont(name: "Helvetica Bold", size: 14.0) 

let textRect: NSRect = NSMakeRect(5, 3, 125, 18) 
let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as NSMutableParagraphStyle 
textStyle.alignment = NSTextAlignment.LeftTextAlignment 
let textColor = NSColor(calibratedRed: 0.147, green: 0.222, blue: 0.162, alpha: 1.0) 

let textFontAttributes = [ 
    NSFontAttributeName: font, 
    NSForegroundColorAttributeName: textColor, 
    NSParagraphStyleAttributeName: textStyle 
] 

text.drawInRect(NSOffsetRect(textRect, 0, 1), withAttributes: textFontAttributes) 

錯誤是本着讓texFontAttributes ...

Cannot convert the expression's type 'Dictionary' to type 'DictionaryLiteralConvertible' 

此代碼完美地工作,直到Xcode的6.1 GM。

當我試圖聲明textFontAttributes作爲NSDictionary的錯誤信息更改爲:

Cannot convert the expression's type 'NSDictionary' to type 'NSString!' 

我不知道如何解決這個問題:(

+0

我不知道爲什麼,但'drawAtPoint:withAttributes:','drawInRect:withAttributes:','drawWithRect:選項:屬性:',' sizeWithAttributes:'和'boundingRectWithSize:options:attributes:'are「在Swift中不可用」 – JDS 2014-10-05 14:05:47

+0

@JDS它在Swift中不可用,但Swift的* String *類型不可用。你可以在* NSString *上調用這些方法,就像OP一樣。 – Blaszard 2015-03-06 12:59:48

回答

22

的問題是,font是可選的,因爲方便contructors現在回到可選值,S Øfont需要被解開在你的字典中的值:

if let actualFont = font { 
    let textFontAttributes = [ 
     NSFontAttributeName: actualFont, 
     NSForegroundColorAttributeName: textColor, 
     NSParagraphStyleAttributeName: textStyle 
    ] 

    text.drawInRect(NSOffsetRect(textRect, 0, 1), withAttributes: textFontAttributes) 
} 
0

我有這樣一段代碼在我應用程序,它沒有問題的工作:

var textAttributes: [String: AnyObject] = [ 
     NSForegroundColorAttributeName : UIColor(white: 1.0, alpha: 1.0).CGColor, 
     NSFontAttributeName : UIFont.systemFontOfSize(17) 
    ] 
+2

在iOS 8中,使用.drawAtPoint:withAttributes,該.CGColor導致崩潰。它期待着一個UIColor。 – bitmusher 2015-08-03 19:57:44

+0

@bitmusher ty,我的應用程序因爲神祕的原因而崩潰,您的評論使我找到了正確的原因。 UIColor,而不是CGColor。你會認爲編譯器可以捕捉到這一點,但是這些屬性被打包到一個字符串數組中是有點危險的,它來自Swift,否則它很挑剔和明確。 – DrZ214 2015-12-21 07:07:09

1

這也是另一種選擇。

let textFontAttributes = [ 
    NSFontAttributeName : font!, 
    NSForegroundColorAttributeName: textColor, 
    NSParagraphStyleAttributeName: textStyle 
] 
0

斯威夫特4

let attributeDict: [NSAttributedStringKey : Any] = [ 
     .font: font!, 
     .foregroundColor: textColor, 
     .paragraphStyle: textStyle, 
    ] 

    text.draw(in: rect, withAttributes: attributeDict)