我创建了两个自定义字体文件(常规和轻字体),并将其添加到我的项目中,并希望动态改变我的字体样式和大小。 图标被映射到字形。
我该如何做到这一点?
var customFont = UIFont(name: "customregular", size: 12.0)
我们都是从某个地方开始的,所以我试着回答你的问题。
首先创建一个新的公共扩展:
import UIKit
public extension UIFont {
func yourCustomFont(withStyle: YourCustomStyle, ofSize: fontSize: CGFloat) -> UIFont {
return UIFont(name: style.fontStyle(), size: fontSize)!
}
}
public enum YourCustomStyle: String {
case light
case regular
func fontStyle() -> String {
switch self {
case .light:
return "customlight"
case .regular:
return "customregular"
}
}
}
public extension String {
func mapGlyphesToIcon(name: YourFont) -> String {
return name.rawValue
}
}
public enum YourFont: String {
case a = "a"
case b = "b"
// and so on
}
通过这种方式,您可以使用特定的样式(例如,轻的,规则的或任何你有的)和大小来调用您的CustomFont。 假设您想为您的按钮分配大小为20的浅色字体:
yourButton.titleLabel?.font = .yourCustomFont(withStyle: .light, ofSize: 20)
现在我们抓取字体的rawValues并将其分配给按钮的titleLabel(您可以在这里阅读更多关于rawVales和枚举的信息)。
我们可以这样做,因为按钮使用自定义字体(上面的代码):
yourButton.setTitle(.mapGlyphesToIcon(name: .a), for: .normal)
按钮应该显示一个浅色字体,标题应该设置为图标,这是映射到字形a。