gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 05:13:14 26 4
gpt4 key购买 nike

我在使用 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)

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

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

最佳答案

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

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

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

关于Swift - 使用 drawInRect 绘制文本 :withAttributes:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26201844/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com