fonts - 从 SwiftUI.Font 转换为 UIFont

标签 fonts swiftui uifont

我有一个 UIViewRepresentableUITextView我想在 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/

相关文章:

ios - 在 SwiftUI 中从 TabView 获取所选标签索引的方法

ios - 相对于屏幕尺寸缩放 UIFont 尺寸

iphone - 检测字体是否为 Serif

Java 字体使用项目错误

html - 无法连接 HTML 页面的字体

xcode - SwiftUI:结构化编辑弹出框(Command + 单击)不显示

java - 更改字体 System.out.println 的大小

dictionary - ListView SwiftUI 的字典数组

iphone - 如何使用 +fontWithName :size: and specify both the font family name and the specific style information for the font? 创建字体

ios - UITextfields 占位符字体未使用 HelveticaNeueLTPro-Roman 字体固定在水平中心位置