问题描述
我发现如果我将属性文本设置为 UILabel
,预定义字体将更改为属性文本的第一个字符的字体。例如:
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?
将字体重置为预定义字体的一种解决方案是设置文本
属性 UILabel
,因为这会导致 UILabel
切换到纯文本模式(不再有属性文本)。 / p>
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
推荐答案
假设让myLabel:UILabel
的字体大小为20. myLabel 应显示属性文本:foo bar,其中bar的字体大小为30。
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.
如果更改 myLabel 上的字体,打算更改字体大小 foo不是20,而是15,相反,你会发现这会导致你的 attributedText
搞砸了。
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.
受@ Majid调查结果的启发,如果在应用字体更改之前设置 text
属性。 attributedText
保持不变,现在更新为新的默认字体!
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
}
}
这篇关于在设置attributedText后阻止自动UILabel字体更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!