我有一个带有
UIViewRepresentable
的 UITextView
,我想使用 SwiftUI 环境中当前的 UITextView
设置 Font
上的字体。我只需要一个简单的初始化,例如:
UIFont(_ swiftUIFont: Font)
但我找不到这样的东西。并且
Font
类型似乎没有任何我可以用来尝试实现的信息。有人知道两种字体表示之间进行转换的方法吗?
有点破解但有效(做另一个方向作为练习留给读者)。
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
}
}
这是卢克·霍华德解决方案的重新格式化,以减少文本量
extension UIFont {
class func preferredFont(from font: Font) -> UIFont {
let style: UIFont.TextStyle
switch font {
case .largeTitle: style = .largeTitle
case .title: style = .title1
case .title2: style = .title2
case .title3: style = .title3
case .headline: style = .headline
case .subheadline: style = .subheadline
case .callout: style = .callout
case .caption: style = .caption1
case .caption2: style = .caption2
case .footnote: style = .footnote
case .body: fallthrough
default: style = .body
}
return UIFont.preferredFont(forTextStyle: style)
}
}
如果您使用的是 5.9 版本的 Swift,则可以使用 switch 语句返回一个值:
extension UIFont {
class func preferredFont(from font: Font) -> UIFont {
let style: UIFont.TextStyle =
switch font {
case .largeTitle: .largeTitle
case .title: .title1
case .title2: .title2
case .title3: .title3
case .headline: .headline
case .subheadline: .subheadline
case .callout: .callout
case .caption: .caption1
case .caption2: .caption2
case .footnote: .footnote
default: .body // Includes .body
}
return UIFont.preferredFont(forTextStyle: style)
}
}
不,你不能,你必须使用传递给
Font
的参数来创建 UIFont