Convert from SwiftUI.Font to UIFont

后端 未结 2 1422
名媛妹妹
名媛妹妹 2020-12-15 06:51

I have a UIViewRepresentable with a UITextView and I want to set the font on the UITextView using the Font from the SwiftUI environment. I just need a simple init like:

相关标签:
2条回答
  • 2020-12-15 06:57

    No you can't, you have to use the params you passed to the Font to create UIFont

    0 讨论(0)
  • 2020-12-15 07:03

    A bit of a hack but works (doing the other direction is left as an exercise to the reader).

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题