Swift NSAttributedStringKey not applying foreground color correctly
Use negative strokeWidth
if you'll set foregroundColor
as well. Otherwise, only the stroke is seen.
let attributes = [
NSAttributedStringKey.strokeColor.rawValue: UIColor.black,
NSAttributedStringKey.backgroundColor.rawValue: UIColor.red,
NSAttributedStringKey.foregroundColor.rawValue: UIColor.white,
NSAttributedStringKey.font.rawValue: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSAttributedStringKey.strokeWidth.rawValue: -4.5]
Swift 5
let attributes = [
NSAttributedString.Key.strokeColor: UIColor.black,
NSAttributedString.Key.backgroundColor: UIColor.red,
NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSAttributedString.Key.strokeWidth: -3.0]
Edit: See rmaddy's comment about why we need the rawValue
in this case below.
Stroke width responsible for this, Negative stroke value can solve your problem.
Swift 4.2
let attributes = [
NSAttributedString.Key.strokeColor.rawValue: UIColor.black,
NSAttributedString.Key.backgroundColor.rawValue: UIColor.red,
NSAttributedString.Key.foregroundColor.rawValue: UIColor.white,
NSAttributedString.Key.font.rawValue: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSAttributedString.Key.strokeWidth.rawValue: -3.0]
Swift 5
let attributes = [
NSAttributedString.Key.strokeColor: UIColor.black,
NSAttributedString.Key.backgroundColor: UIColor.red,
NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSAttributedString.Key.strokeWidth: -3.0]