let fontSize: CGFloat = 24
// Here we get San Francisco with the desired weight
let systemFont = UIFont.systemFont(ofSize: fontSize, weight: .regular)
// Will be SF Compact or standard SF in case of failure.
let font: UIFont
if let descriptor = systemFont.fontDescriptor.withDesign(.rounded) {
font = UIFont(descriptor: descriptor, size: fontSize)
} else {
font = systemFont
}
func roundedFont(ofSize style: UIFont.TextStyle, weight: UIFont.Weight) -> UIFont {
// Will be SF Compact or standard SF in case of failure.
let fontSize = UIFont.preferredFont(forTextStyle: style).pointSize
if let descriptor = UIFont.systemFont(ofSize: fontSize, weight: weight).fontDescriptor.withDesign(.rounded) {
return UIFont(descriptor: descriptor, size: fontSize)
} else {
return UIFont.preferredFont(forTextStyle: style)
}
}
6条答案
按热度按时间7gs2gvoe1#
2o7dmzc52#
我知道这个问题是关于SwiftUI的,但我认为包括UIKit答案可能会有所帮助。
vuv7lop33#
这样做对我来说在
SwiftUI
中的Text
对象上是有效的:.font(.system(size: 13.0, weight: .regular, design: .rounded))
ej83mcc04#
将@Pomme2Poule的UIKit答案转换为易于使用的函数,如果有人需要它。函数也使用动态类型,因此它将随字体大小缩放。
q3qa4bjr5#
我想添加一个额外的用例:如果您希望在保持动态字体缩放的同时,将自定义字体粗细应用于文本字段等四舍五入的SF字体,可以执行以下操作:
这是必需的,因为用户不能直接在
TextField
上调用.fontWeight()
(至少从iOS 13开始)。z18hc3ub6#
iOS 16.1
使用fontDesign(.rounded)