ios 如何在不更改字体大小的情况下快速更改 UILabel 的字体?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31090983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I change the font of a UILabel in swift without changing the font size?
提问by Matt Spoon
I have programatically created a label which I have set the adjustsToFitWidth to true. Now I want to change its font, but I can't do that without making the font size of the label constant. Does anybody know how I could change only the font and not the font size of a UILabel in swift?
我已经以编程方式创建了一个标签,我已将 adjustsToFitWidth 设置为 true。现在我想更改它的字体,但如果不使标签的字体大小保持不变,我就无法做到这一点。有谁知道我如何快速更改 UILabel 的字体而不是字体大小?
回答by Aeradriel
Why not get the font size, and specify a new font with this value ?
为什么不获取字体大小,并使用此值指定新字体?
let fontSize = self.label.font.pointSize;
self.label.font = UIFont(name: "HelveticaNeue", size: fontSize)
回答by iYoung
You can do it like this:
你可以这样做:
label.font = UIFont(name: "Arial", size: label.font.pointSize)
This will use the same font size, "Arial" can be whatever family you want to choose.
这将使用相同的字体大小,“Arial”可以是您想要选择的任何系列。
回答by A.G
An improved answer.
一个改进的答案。
UILabel Subclassing: Add an empty swift file and name it. e.g..EZLabel. Add the following code.
UILabel 子类化:添加一个空的 swift 文件并为其命名。例如。EZLabel。添加以下代码。
import Foundation
import UIKit
class EZLabel: UILabel {
override func awakeFromNib() {
super.awakeFromNib()
changeFontName()
}
func changeFontName()
{
self.font = UIFont(name: "Roboto", size: self.font.pointSize)
}
}
The advantage is that you don't need to change each UILabel's font in the whole project if needed.
好处是如果需要的话,你不需要在整个项目中更改每个 UILabel 的字体。
回答by Ahmed Samir
extension UILabel {
override open func awakeFromNib() {
super.awakeFromNib()
changeFontName()
}
func changeFontName()
{
self.font = UIFont(name: "YOUR_FONT_NAME", size: self.font.pointSize)
}
}
/* Do this also for buttons and any uiviews */