Bhavik P. Bhavik P. - 6 months ago 4x
Swift Question

IOS Anyway to have NSAttributedString throughout app. Swift

I have a font which is super skinny. In photoshop, I have added stroke to the font which makes it look more appealing. When transferring it to iOS I couldn't add a stroke unless I used NSAttributedString. By using the NSAttributedString I got one of my UILabels to look exactly how it looks in photoshop however the issue is that I will have hundreds of UILabels by the time my app is finished. Is there a way where I don't have to manually connect each UILabel to its respective controller and set its attributedText one by one. Any suggestions would help.


Based on @AdamPro13 suggestion, you could create a protocol extension for your NSAttributedString:

So, create NSAttributedStringExtension.swift with something like that:

protocol NSAttributedStringExtension {
    static func attributed(string:String, font:UIFont, color:UIColor) -> NSAttributedString

extension NSAttributedString : NSAttributedStringExtension {
    class func attributed(string:String, font:UIFont, color:UIColor) -> NSAttributedString {

        let attrs = [NSFontAttributeName:font, NSForegroundColorAttributeName:color]
        return NSAttributedString(string: string, attributes: attrs)

And you could make several different functions for different label types. Just apply then on your label (rough code):

let label:UILabel
let font:UIFont
let color:UIColor
label.attributedText = NSAttributedString.attributed("test", font: font, color: color)

Note: the font and colour you could setup in your protocol extension function