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
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. TheattributedText
stays intact, and now updated with a new "default" font!Is responsible for choosing which characters
has an effect on. When you set
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
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.