![](/img/trans.png)
[英]How to use dynamic colors in attributed strings via interface builder?
[英]How to use SF Fonts with attributed text in Interface Builder
我在Xcode 9.x上,我想在UILabel上使用属性文本(在InterfaceBuilder中)。
我想设置:系统字体(San Fracisco)和一些粗体风格的单词。 但它不起作用( 斜体有效,但不大胆 ......)。
我不能选择系统字体(旧金山专业版/显示版),除非我在Xcode项目中导入所有旧金山字体(但它很重:15Mb!)
你觉得怎么样? 谢谢。
通过直接编辑XML,我能够完全通过Interface Builder(有点)破解我的方式。 根据需要设置您的属性字符串,然后找到<font />
并根据需要进行编辑。 例如,我的按钮使用系统粗体字体。 现在,字体显示在IB中,无论是在属性字符串的可视化渲染中,还是在属性中。 我可以更改大小,并保持粗体字体。
<font key="NSFont" size="16" name=".AppleSystemUIFontBold"/>
这是在上下文中:
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" lineBreakMode="wordWrap" hasAttributedTitle="YES" translatesAutoresizingMaskIntoConstraints="NO" id="1mt-rM-2b8">
<rect key="frame" x="211" y="8" width="187" height="52"/>
<color key="backgroundColor" red="0.0" green="0.41960784309999999" blue="0.72156862749999995" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<inset key="contentEdgeInsets" minX="4" minY="16" maxX="4" maxY="16"/>
<state key="normal">
<attributedString key="attributedTitle">
<fragment content="Okay, I'll fill it out now">
<attributes>
<color key="NSColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<font key="NSFont" size="16" name=".AppleSystemUIFontBold"/>
</attributes>
</fragment>
</attributedString>
</state>
<connections>
...
</connections>
</button>
据我所知,你不能在Interface Builder中严格执行。
但是,如果您是封闭视图或标签视图本身的子类,则可以轻松地重置awakeFromNib()中的字体,同时仍然保留Interface Builder中用于标签的其余设置。 这将节省您以编程方式从头开始创建它。
像往常一样在IB中设置标签,包括属性,约束,操作。 使用任意字体进行预览。 确保按住Ctrl键并拖动样式标签的插座,然后使用以下代码切换awakeFromNib中的字体。 当您的应用程序运行时,它将使用系统字体,以及您已在IB中建立的所有属性,位置约束等。
[编辑:更正为添加粗体字体重,不会从IB继承。]
例如:
class EnclosingViewSubclass : UIView {
// The outlet you create for the label
@IBOutlet weak var styledLabel: UILabel!
// ...
override func awakeFromNib() {
super.awakeFromNib()
// setting the label's font face to the system font, including picking
// up the font-size you establish in InterfaceBuilder
styledLabel.font = UIFont.systemFont(ofSize: styledLabel.font.pointSize,
weight: UIFontWeightBold)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.