Swift中UITextView设置Font字体的方法及SwiftUI替代方案咨询
解决方案
一、将SwiftUI的Font转换为UIKit的UIFont
SwiftUI的Font是对UIKit字体的封装,但没有直接提供转UIFont的API,可根据字体类型分别处理:
1. 系统字体转换
对于.largeTitle、.body这类系统预设字体,可直接映射到UIKit对应的文本样式:
extension Font { func toUIFont() -> UIFont { let textStyle: UIFont.TextStyle switch self { case .largeTitle: textStyle = .largeTitle case .title: textStyle = .title1 case .title2: textStyle = .title2 case .title3: textStyle = .title3 case .headline: textStyle = .headline case .subheadline: textStyle = .subheadline case .body: textStyle = .body case .callout: textStyle = .callout case .footnote: textStyle = .footnote case .caption: textStyle = .caption1 case .caption2: textStyle = .caption2 default: textStyle = .body } return UIFont.preferredFont(forTextStyle: textStyle) } }
2. 自定义字体转换
如果使用Font.custom("FontName", size: 16)这类自定义字体,直接通过相同的字体名称和大小创建UIFont即可,两者共用同一字体标识:
// SwiftUI自定义字体 let swiftUIFont = Font.custom("ArialMT", size: 16) // 对应UIFont创建方式 let uiFont = UIFont(name: "ArialMT", size: 16)
二、SwiftUI中替代UITextView的控件
若不想在两种字体类型间转换,推荐使用SwiftUI原生的TextEditor控件——它完全支持SwiftUI的Font类,且具备和UITextView一致的核心功能(多行编辑、滚动、文本选择等):
struct ContentView: View { @State private var text = "编辑你的文本..." var body: some View { TextEditor(text: $text) .font(.custom("ArialMT", size: 16)) // 直接使用SwiftUI的Font .padding() .background(Color(UIColor.systemGray6)) .cornerRadius(8) } }
注:TextEditor默认无占位符功能,可通过叠加文本实现;默认样式也可通过修饰符自定义调整。
内容的提问来源于stack exchange,提问作者Strassenrenner
相关产品推荐
相关产品推荐

