我有一个 UIViewRepresentable
与 UITextView
我想在 UITextView
上设置字体使用当前 Font
来自 SwiftUI 环境。我只需要一个简单的初始化,如:
UIFont(_ swiftUIFont: Font)
但我找不到任何这样的东西。和 Font
type 似乎没有任何信息我可以用来尝试实现一个。有人知道在两种字体表示之间进行转换的方法吗?
最佳答案
有点黑客但有效(做另一个方向留给读者作为练习)。
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
}
}
关于fonts - 从 SwiftUI.Font 转换为 UIFont,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60049927/