Prevent automatic changes to the UILabel font after setting the Text attribute

I realized that if I set the attribute text to UILabel, the predefined font will be changed to the font of the first character of the attributed text. eg:

// the font size is set to 20 in Interface Builder
println(theLabel.font.pointSize);
var styledText = NSMutableAttributedString(string: "$100");
var smallFont = UIFont(name: theLabel.font.fontName, size: theLabel.font.pointSize / 2)!;
styledText.addAttribute(NSFontAttributeName, value: smallFont, range: NSMakeRange(0, 1));
theLabel.attributedText = styledText;
println(theLabel.font.pointSize);
// output:
// 20
// 10

I do not know if this can be called a mistake or not, but in some cases this causes a problem.

Can anyone suggest a clean solution for getting the default font installed in the interface builder?

One solution to reset the font for a predefined font is to set the property text UILabel, because it leads to the fact that it UILabelswitches to plain text mode (no longer with attribute text).

theLabel.text = ""; // reset the font
println(theLabel.font.pointSize);
// output:
// 20
+4
2

, let myLabel: UILabel 20. myLabel : "foo bar", "bar" 30.

myLabel, "foo", 20, 15, , , attributedText .

@Majid, text, . attributedText , !

func setFont(_ font: UIFont, keepAttributes: Bool = true) {
    // Store attributedText before it gets ruined by font change
    let attributed = attributedText
    if attributed != nil && keepAttributes {
        // This trick enables us to change "default" font for our attributedText.
        text = ""
    }
    // Apply font change
    self.font = font.font
    if keepAttributes {
        // Restore attribute text, now with a new `default` font
        attributedText = attributed
    }
}
+1
NSMakeRange 

addAttribute

.

NSMakeRange(0,1)

0- 1- , . , .

NSMakeRange(0,i)   //or     NSMakeRange(0,1000)    

alt. option to 1000, , , "i" .

p.s. // , .

-1

Source: https://habr.com/ru/post/1583938/


All Articles