从SwiftUI.Font转换为UIFont

时间:2020-02-04 02:56:37

标签: swiftui uifont

我有一个带有UITextView的UIViewRepresentable,我想使用SwiftUI环境中的Font在UITextView上设置字体。我只需要一个简单的初始化,如:

UIFont(_ swiftUIFont: Font)

但是我找不到任何这样的东西。而且Font类型似乎没有任何我可以用来实现的信息。有人知道两者之间转换的方法吗?

2 个答案:

答案 0 :(得分:2)

有点骇人听闻但可行(将另一个方向留给读者练习)

extension UIFont {
    class func with(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
    }
}

答案 1 :(得分:1)

不,您不能使用传递给Font的参数来创建UIFont