Outline UILabel text in UILabel Subclass
@anandnimje answer converted to Swift 4.2 and wrapped it into a function:
public func stroke(font: UIFont, strokeWidth: Float, insideColor: UIColor, strokeColor: UIColor) -> [NSAttributedStringKey: Any]{
return [
NSAttributedStringKey.strokeColor : strokeColor,
NSAttributedStringKey.foregroundColor : insideColor,
NSAttributedStringKey.strokeWidth : -strokeWidth,
NSAttributedStringKey.font : font
]
}
Usage:
label.attributedText = NSMutableAttributedString(string: "Hello World",
attributes: stroke(font: UIFont(name: "SourceSansPro-Black", size: 20)!,
strokeWidth: 4, insideColor: .white, strokeColor: .black))
Make sure you have the right name for your UIFont, else it crashes. Should never be a problem if you have the right name.
This code works for me.
Swift 3
let strokeTextAttributes = [
NSStrokeColorAttributeName : UIColor.black,
NSForegroundColorAttributeName : UIColor.white,
NSStrokeWidthAttributeName : -4.0,
NSFontAttributeName : UIFont.boldSystemFont(ofSize: 30)
] as [String : Any]
myLabel.attributedText = NSMutableAttributedString(string: "Test me i have color.", attributes: strokeTextAttributes)
Swift 4.2 & 5.1
let strokeTextAttributes = [
NSAttributedString.Key.strokeColor : UIColor.red,
NSAttributedString.Key.foregroundColor : UIColor.white,
NSAttributedString.Key.strokeWidth : -4.0,
NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 30)]
as [NSAttributedString.Key : Any]
labelOutLine.attributedText = NSMutableAttributedString(string: "Your outline text", attributes: strokeTextAttributes)