以编程方式
不使用storyboard,我有一个方法可以根据屏幕宽度简单地更改字体大小:
func dynamicFontSize(_ FontSize: CGFloat) -> CGFloat {
let screenWidth = UIScreen.main.bounds.size.width
let calculatedFontSize = screenWidth / 375 * FontSize
return calculatedFontSize
}
并且可以用作:
myLabel.font = UIFont(name: "Helvetica", size: dynamicFontSize(20))
dynamicFontSize
函数中,数字 375 只是字体大小计算的基础,因为我通常在 iPhone 8 上测试我的应用程序(即由于其实际宽度为 375,字体大小 18 实际上 在 iPhone 8 上为 18)。此数字可根据您的喜好进行更改。UILabel
并使用 @IBInspectable
,如下所示:import UIKit
class UILabelFontClass: UILabel {
@IBInspectable var DynamicFontSize: CGFloat = 0 {
didSet {
overrideFontSize(FontSize: DynamicFontSize)
}
}
func overrideFontSize(FontSize: CGFloat){
let fontName = self.font.fontName
let screenWidth = UIScreen.main.bounds.size.width
let calculatedFontSize = screenWidth / 375 * FontSize
self.font = UIFont(name: fontName, size: calculatedFontSize)
}
}
将 UILabelFontClass
子类化到你的标签中:
现在在属性检查器中,您可以设置字体大小:
不必为UILabel创建不同的类。您可以创建UILabel 扩展并使用此IBDesignable解决方案从Storyboard中设置值。
这里的基础宽度为375pt
extension UILabel{
@IBInspectable
var scaleSize: CGFloat {
set {
let fontName = self.font.fontName
let screenWidth = UIScreen.main.bounds.size.width
let calculatedFontSize = screenWidth / 375 * newValue
self.font = UIFont(name: fontName, size: calculatedFontSize)
}
get {
return self.scaleSize
}
}
}