prevent automatic UILabel font changes after setti

2019-04-09 18:35发布

I've figured out that if I set an attributed text to an UILabel, the predefined font will be changed to the font of the first character of attributed text. for example:

// 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've no idea if it could be called a bug or not, but it causes problem in some cases.

Can anybody suggest a clean solution to obtain the default font that have set in the Interface Builder?

One solution to reset the font to predefined font is to set the text property of UILabel, because that causes the UILabel to switch to the plain text mode (no attributed text anymore).

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

2条回答
ら.Afraid
2楼-- · 2019-04-09 18:52

Let say that let myLabel: UILabel have a font size of 20. myLabel should display an attributed text: "foo bar", where "bar" has font size of 30.

If you change the font on myLabel, with the intention to change the font size of "foo" to not be 20, but rather 15 instead, you will notice that this results in your attributedText being messed up.

Inspired by @Majid's findings, if you set the text property before applying the font change. The attributedText stays intact, and now updated with a new "default" font!

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
    }
}
查看更多
男人必须洒脱
3楼-- · 2019-04-09 18:59
NSMakeRange 

Is responsible for choosing which characters

addAttribute

has an effect on. When you set

NSMakeRange(0,1)

it tells every character from the 0th character to the 1st character to be attributed. Which means only the first character can be attributed. Try setting it to

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

I set the alt. option to 1000 because it is an arbitrarily large number giving a guaranteed font change just in case "i" does not work

p.s. the // symbol refers to a helpful hint or comment the previous developers wrote down.

查看更多
登录 后发表回答