Swift - 使用drawInRect绘制文本:withAttributes:

时间:2014-10-05 10:44:26

标签: swift

我对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)

错误在行中让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!'

我不知道如何解决这个问题:(

5 个答案:

答案 0 :(得分:24)

问题是font是可选的,因为方便构造函数现在返回可选值,因此需要将font解包为字典中的值:

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

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

答案 1 :(得分:4)

Swift 4

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

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

答案 2 :(得分:2)

这也是另一种选择。

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

答案 3 :(得分:0)

我的应用程序中有这段代码可以正常运行:

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

答案 4 :(得分:0)

在XCode 12中,Swift 5.3。我找不到String对象的draw方法。 在我手动转换为NSString之后,它对我有用。

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