Swift - рисование текста с помощью drawInRect: withAttributes:
У меня странная проблема с 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 type 'Dictionary' to type 'DictionaryLiteralConvertible'
Этот код отлично работает до Xcode 6.1 GM.
Когда я пытаюсь объявить textFontAttributes, поскольку сообщение об ошибке NSDictionary изменено на:
Cannot convert the expression type 'NSDictionary' to type 'NSString!'
Я не знаю, как решить эту проблему: (
Ответы
Ответ 1
Проблема заключается в том, что font
не является обязательным, потому что конструкторы удобства теперь возвращают необязательные значения, поэтому font
необходимо развернуть как значение в словаре:
if let actualFont = font {
let textFontAttributes = [
NSFontAttributeName: actualFont,
NSForegroundColorAttributeName: textColor,
NSParagraphStyleAttributeName: textStyle
]
text.drawInRect(NSOffsetRect(textRect, 0, 1), withAttributes: textFontAttributes)
}
Ответ 2
В Swift 4
let attributeDict: [NSAttributedString.Key : Any] = [
.font: font!,
.foregroundColor: textColor,
.paragraphStyle: textStyle,
]
text.draw(in: rect, withAttributes: attributeDict)
Ответ 3
Это еще один вариант.
let textFontAttributes = [
NSFontAttributeName : font!,
NSForegroundColorAttributeName: textColor,
NSParagraphStyleAttributeName: textStyle
]
Ответ 4
У меня есть эта часть кода в моем приложении, которая работает без проблем:
var textAttributes: [String: AnyObject] = [
NSForegroundColorAttributeName : UIColor(white: 1.0, alpha: 1.0).CGColor,
NSFontAttributeName : UIFont.systemFontOfSize(17)
]