iPera
iPera

Reputation: 1073

Swift - Drawing text with drawInRect:withAttributes:

I have strange problem with Xcode 6.1 GM.

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)

Error is in line let texFontAttributes...

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

This code is worked perfectly until Xcode 6.1 GM.

When I'm tried to declare textFontAttributes as NSDictionary error message is changed to:

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

I have no idea how to solve this problem :(

Upvotes: 22

Views: 34359

Answers (5)

Li Jin
Li Jin

Reputation: 2167

In XCode 12, Swift 5.3. i was not able to find the draw method for String object. After i manually cast to NSString, it worked for me.

let text: String = "XXX"
(text as NSString).draw(in: rect withAttributes: attributes)

Upvotes: 1

AechoLiu
AechoLiu

Reputation: 18428

In Swift 4

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

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

Upvotes: 8

Randall Sutton
Randall Sutton

Reputation: 1895

This is also another option.

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

Upvotes: 2

vacawama
vacawama

Reputation: 154741

The problem is that font is optional because the convenience contructors now return optional values, so font needs to be unwrapped to be a value in your dictionary:

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

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

Upvotes: 26

zisoft
zisoft

Reputation: 23078

I have this piece of code in my app which works without problems:

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

Upvotes: 0

Related Questions