从SwiftUI.Font转换为UIFont [英] Convert from SwiftUI.Font to UIFont
本文介绍了从SwiftUI.Font转换为UIFont的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 UIViewRepresentable
和一个 UITextView
,并且我想使用当前的 Font 设置字体在
UITextView
上代码>来自SwiftUI环境.我只需要一个简单的初始化,如:
I have a UIViewRepresentable
with a UITextView
and I want to set the font on the UITextView
using the current Font
from the SwiftUI environment. I just need a simple init like:
UIFont(_ swiftUIFont: Font)
但是我找不到任何这样的东西.而且 Font
类型似乎没有任何我可以用来实现的信息.有人知道在两种字体表示之间进行转换的方法吗?
But I can't find any such thing. And the Font
type doesn't seem to have any information I can use to try to implement one. Anyone know of a way to convert between the two font representations?
推荐答案
有些破绽,但可以解决(做另一个方向留给读者练习).
A bit of a hack but works (doing the other direction is left as an exercise to the reader).
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
}
}
这篇关于从SwiftUI.Font转换为UIFont的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文