kesape
kesape

Reputation: 159

UILabel, NSMutableParagraphStyle(), NSAttributedString

i am trying to use UIlabel extension + String extension to get a summary result, but lost some of settings of it

Here is UILabel extenstion

extension UILabel {

    static func insultString() -> UILabel {
        let label = UILabel()
        label.lineBreakMode = .byWordWrapping
        label.numberOfLines = 0
        label.textAlignment = .center
        label.font = AppFonts.regular17.font
        label.adjustsFontSizeToFitWidth = true
        label.minimumScaleFactor = 0.7
        label.lineBreakMode = .byClipping
        label.sizeToFit()
        return label

    }
}

Here is how i use it in my code

private var insultLabel = UILabel.insultString()

Here is String extension

extension String {

    static func stringConfig(_ label: String) -> NSAttributedString {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineHeightMultiple = 1.35

        let string = NSMutableAttributedString(string: label, attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])

        return string
    }
}

and here is how i use it in my code

self.insultLabel.attributedText = String.stringConfig(self.presenter?.insults.savedInsults.last ?? "No insults")

The problem is i correctly get a font and size of my string, but i lost label.textAlignment = .center, label.adjustsFontSizeToFitWidth = true, and so on... Why it happens?

Upvotes: 1

Views: 764

Answers (1)

Vadim Belyaev
Vadim Belyaev

Reputation: 2869

In NSAttributedString, each paragraph can have its own text alignment, so you need to set it in the paragraphStyle:

paragraphStyle.alignment = .center

When it comes to adjustsFontSizeToFitWidth, I don't think it works with attributed text because UILabel no longer owns the font size in this case. It's not documented explicitly but makes sense to me.

Similarly, some other properties that you're setting to your label when constructing it will be ignored because they are managed by the attributed string.

Upvotes: 1

Related Questions