Ric*_*ble 28 fonts uifont swiftui
我有一个UIViewRepresentable,UITextView我想UITextView使用FontSwiftUI 环境中的当前设置字体。我只需要一个简单的初始化,如:
UIFont(_ swiftUIFont: Font)
Run Code Online (Sandbox Code Playgroud)
但我找不到任何这样的东西。而且该Font类型似乎没有任何我可以用来尝试实现一个的信息。有人知道在两种字体表示之间进行转换的方法吗?
Mar*_*ius 12
这是卢克霍华德解决方案的重新格式化,以减少文本量
extension UIFont {
class func preferredFont(from font: Font) -> UIFont {
let style: UIFont.TextStyle
switch font {
case .largeTitle: style = .largeTitle
case .title: style = .title1
case .title2: style = .title2
case .title3: style = .title3
case .headline: style = .headline
case .subheadline: style = .subheadline
case .callout: style = .callout
case .caption: style = .caption1
case .caption2: style = .caption2
case .footnote: style = .footnote
case .body: fallthrough
default: style = .body
}
return UIFont.preferredFont(forTextStyle: style)
}
}
Run Code Online (Sandbox Code Playgroud)
从 Swift 5.9 开始,您可以使用 switch 语句返回一个值,并且外观更加简洁:
extension UIFont {
class func preferredFont(from font: Font) -> UIFont {
let style: UIFont.TextStyle =
switch font {
case .largeTitle: .largeTitle
case .title: .title1
case .title2: .title2
case .title3: .title3
case .headline: .headline
case .subheadline: .subheadline
case .callout: .callout
case .caption: .caption1
case .caption2: .caption2
case .footnote: .footnote
default: /*.body */ .body
}
return UIFont.preferredFont(forTextStyle: style)
}
}
Run Code Online (Sandbox Code Playgroud)
有点黑客但有效(做另一个方向留给读者作为练习)。
extension UIFont {
class func preferredFont(from font: Font) -> UIFont {
let uiFont: UIFont
switch font {
case .largeTitle:
uiFont = UIFont.preferredFont(forTextStyle: .largeTitle)
case .title:
uiFont = UIFont.preferredFont(forTextStyle: .title1)
case .title2:
uiFont = UIFont.preferredFont(forTextStyle: .title2)
case .title3:
uiFont = UIFont.preferredFont(forTextStyle: .title3)
case .headline:
uiFont = UIFont.preferredFont(forTextStyle: .headline)
case .subheadline:
uiFont = UIFont.preferredFont(forTextStyle: .subheadline)
case .callout:
uiFont = UIFont.preferredFont(forTextStyle: .callout)
case .caption:
uiFont = UIFont.preferredFont(forTextStyle: .caption1)
case .caption2:
uiFont = UIFont.preferredFont(forTextStyle: .caption2)
case .footnote:
uiFont = UIFont.preferredFont(forTextStyle: .footnote)
case .body:
fallthrough
default:
uiFont = UIFont.preferredFont(forTextStyle: .body)
}
return uiFont
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6677 次 |
| 最近记录: |