首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Swift -使用drawInRect:withAttributes绘制文本:

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

Stack Overflow用户
提问于 2014-10-05 18:44:26
回答 4查看 32.3K关注 0票数 22

我对Xcode6.1GM有个奇怪的问题。

代码语言:javascript
复制
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...

代码语言:javascript
复制
Cannot convert the expression's type 'Dictionary' to type 'DictionaryLiteralConvertible'

这段代码在Xcode6.1GM之前一直运行得很好。

当我尝试将textFontAttributes声明为NSDictionary时,错误消息更改为:

代码语言:javascript
复制
Cannot convert the expression's type 'NSDictionary' to type 'NSString!'

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-10-05 21:35:08

问题是font是可选的,因为方便的构造器现在返回可选值,所以font需要被解包才能成为字典中的值:

代码语言:javascript
复制
if let actualFont = font {
    let textFontAttributes = [
        NSFontAttributeName: actualFont,
        NSForegroundColorAttributeName: textColor,
        NSParagraphStyleAttributeName: textStyle
    ]

    text.drawInRect(NSOffsetRect(textRect, 0, 1), withAttributes: textFontAttributes)
}
票数 26
EN

Stack Overflow用户

发布于 2014-10-29 03:06:29

这也是另一种选择。

代码语言:javascript
复制
let textFontAttributes = [
    NSFontAttributeName : font!,
    NSForegroundColorAttributeName: textColor,
    NSParagraphStyleAttributeName: textStyle
]
票数 2
EN

Stack Overflow用户

发布于 2014-10-05 19:04:14

我的应用程序中有这段代码,它可以正常工作:

代码语言:javascript
复制
    var textAttributes: [String: AnyObject] = [
        NSForegroundColorAttributeName : UIColor(white: 1.0, alpha: 1.0).CGColor,
        NSFontAttributeName : UIFont.systemFontOfSize(17)
    ]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26201844

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档