Swift - Drawing text with drawInRect:withAttributes:
The problem is that font
is optional because the convenience contructors now return optional values, so font
needs to be unwrapped to be a value in your dictionary:
if let actualFont = font {
let textFontAttributes = [
NSFontAttributeName: actualFont,
NSForegroundColorAttributeName: textColor,
NSParagraphStyleAttributeName: textStyle
]
text.drawInRect(NSOffsetRect(textRect, 0, 1), withAttributes: textFontAttributes)
}
In Swift 4
let attributeDict: [NSAttributedString.Key : Any] = [
.font: font!,
.foregroundColor: textColor,
.paragraphStyle: textStyle,
]
text.draw(in: rect, withAttributes: attributeDict)
This is also another option.
let textFontAttributes = [
NSFontAttributeName : font!,
NSForegroundColorAttributeName: textColor,
NSParagraphStyleAttributeName: textStyle
]