我正在尝试添加重量为“ Heavy”(不是粗体)的系统字体,并且还尝试使其变为斜体。我看到了其他stackoverflow解决方案,但它似乎不起作用。这是我所做的:
let percentageLabel: UILabel = {
let label = UILabel()
label.text = "0"
label.textAlignment = .center
label.textColor = .white
label.font = UIFont.systemFont(ofSize: 32, weight: .heavy, traits: .traitItalic)
return label
}()
堆栈溢出后建议的扩展
extension UIFont {
static func systemFont(ofSize: CGFloat, weight: UIFont.Weight, traits: UIFontDescriptor.SymbolicTraits) -> UIFont? {
let font = UIFont.systemFont(ofSize: ofSize, weight: weight)
if let descriptor = font.fontDescriptor.withSymbolicTraits(traits) {
return UIFont(descriptor: descriptor, size: ofSize)
}
return nil
}
}
问题是当我尝试了所有建议的解决方案时,粗体和斜体似乎可行,但黑色却不起作用。它仍然呈现为常规斜体。
答案 0 :(得分:0)
尝试一下
label.font = UIFont.systemFont(ofSize: 32, weight: .black, traits: .traitItalic)
//If you just want Italic then use this
labelInfo.font = UIFont.italicSystemFont(ofSize: 32)
答案 1 :(得分:0)
Swift 5.0
extension UIFont {
static func systemFontItalic(size fontSize: CGFloat = 17.0, fontWeight: UIFont.Weight = .regular) -> UIFont {
let font = UIFont.systemFont(ofSize: fontSize, weight: fontWeight)
return UIFont(descriptor: font.fontDescriptor.withSymbolicTraits(.traitItalic)!, size: fontSize)
}
}
用法:
label.font = UIFont.systemFontItalic(size: 20.0, fontWeight: .black)
输出:
答案 2 :(得分:0)
Swift 5.*
extension UIFont {
class func italicSystemFont(ofSize size: CGFloat, weight: UIFont.Weight = .regular)-> UIFont {
let font = UIFont.systemFont(ofSize: size, weight: weight)
switch weight {
case .ultraLight, .light, .thin, .regular:
return font.withTraits(.traitItalic, ofSize: size)
case .medium, .semibold, .bold, .heavy, .black:
return font.withTraits(.traitBold, .traitItalic, ofSize: size)
default:
return UIFont.italicSystemFont(ofSize: size)
}
}
func withTraits(_ traits: UIFontDescriptor.SymbolicTraits..., ofSize size: CGFloat) -> UIFont {
let descriptor = self.fontDescriptor
.withSymbolicTraits(UIFontDescriptor.SymbolicTraits(traits))
return UIFont(descriptor: descriptor!, size: size)
}
}
用法:
myLabel.font = UIFont.italicSystemFont(ofSize: 34, weight: .black)