我对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)
Run Code Online (Sandbox Code Playgroud)
错误是在行中让texFontAttributes ...
Cannot convert the expression's type 'Dictionary' to type 'DictionaryLiteralConvertible'
Run Code Online (Sandbox Code Playgroud)
这段代码完美地运行到Xcode 6.1 GM.
当我尝试将textFontAttributes声明为NSDictionary错误消息更改为:
Cannot convert the expression's type 'NSDictionary' to type 'NSString!'
Run Code Online (Sandbox Code Playgroud)
我不知道如何解决这个问题:(
vac*_*ama 25
问题是它font
是可选的,因为方便构造函数现在返回可选值,因此font
需要将其解包为字典中的值:
if let actualFont = font {
let textFontAttributes = [
NSFontAttributeName: actualFont,
NSForegroundColorAttributeName: textColor,
NSParagraphStyleAttributeName: textStyle
]
text.drawInRect(NSOffsetRect(textRect, 0, 1), withAttributes: textFontAttributes)
}
Run Code Online (Sandbox Code Playgroud)
在Swift 4中
let attributeDict: [NSAttributedString.Key : Any] = [
.font: font!,
.foregroundColor: textColor,
.paragraphStyle: textStyle,
]
text.draw(in: rect, withAttributes: attributeDict)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28421 次 |
最近记录: |