Hek*_*kes 6 uikit uilabel swift
我有一个标签,我花了很多时间尝试将 UILabel 的字体更改为 SF Rounded Bold。
喜欢titleLabel.font = UIFont(name: "SFRounded-Bold", size: 34.0)
或titleLabel.font = UIFont(name: "SanFranciscoRounded-Bold ", size: 34.0)
不工作的事情。
甚至可以在 UIKit 中使用 SF Rounded 吗?它没有列在场景编辑器的字体列表中,也没有人问过如何使用它,但在 SwiftUI 中,我可以毫无问题地使用 SF Rounded。
小智 8
斯威夫特 5,iOS 13+
这是另一个帖子的答案的扩展版本
import UIKit
extension UIFont {
class func rounded(ofSize size: CGFloat, weight: UIFont.Weight) -> UIFont {
let systemFont = UIFont.systemFont(ofSize: size, weight: weight)
let font: UIFont
if let descriptor = systemFont.fontDescriptor.withDesign(.rounded) {
font = UIFont(descriptor: descriptor, size: size)
} else {
font = systemFont
}
return font
}
}
Run Code Online (Sandbox Code Playgroud)
要使用它:
let label = UILabel()
label.text = "Hello world!"
label.font = .rounded(ofSize: 16, weight: .regular)
Run Code Online (Sandbox Code Playgroud)
凯文答案的更简洁版本:
import UIKit
extension UIFont {
class func rounded(ofSize size: CGFloat, weight: UIFont.Weight) -> UIFont {
let systemFont = UIFont.systemFont(ofSize: size, weight: weight)
guard #available(iOS 13.0, *), let descriptor = systemFont.fontDescriptor.withDesign(.rounded) else { return systemFont }
return UIFont(descriptor: descriptor, size: size)
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
let label = UILabel()
label.font = .rounded(ofSize: 16, weight: .regular)
Run Code Online (Sandbox Code Playgroud)