iOS 15+ 下如何缩进TextEditor的输入文本?
解决iOS 15+下TextEditor输入文本缩进问题
由于iOS 15的TextEditor没有直接提供文本缩进的API,直接添加.padding()只会给编辑器框架添加边距,无法调整输入文本的位置。可以通过以下两种方法实现输入文本的缩进:
方法1:自定义TextEditor(推荐,不影响全局)
通过UIViewRepresentable封装原生UITextView,直接设置文本容器的内边距,精准控制输入文本的缩进:
struct IndentedTextEditor: UIViewRepresentable { @Binding var text: String var insets: UIEdgeInsets func makeUIView(context: Context) -> UITextView { let textView = UITextView() textView.textContainerInset = insets textView.font = UIFont.preferredFont(forTextStyle: .body) // 匹配SwiftUI默认字体样式 textView.backgroundColor = .clear // 保持SwiftUI背景设置效果 return textView } func updateUIView(_ uiView: UITextView, context: Context) { uiView.text = text uiView.delegate = context.coordinator } func makeCoordinator() -> Coordinator { Coordinator(self) } class Coordinator: NSObject, UITextViewDelegate { var parent: IndentedTextEditor init(_ parent: IndentedTextEditor) { self.parent = parent } func textViewDidChange(_ textView: UITextView) { parent.text = textView.text } } } // 使用示例 IndentedTextEditor(text: $yourTextBinding, insets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)) .frame(height: 100) .cornerRadius(14)
方法2:全局设置UITextView外观(影响所有TextEditor)
如果你的应用中所有TextEditor都需要相同的缩进,可以在App启动时设置全局外观:
// 在App初始化方法或SceneDelegate中添加 UITextView.appearance().textContainerInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) UITextView.appearance().backgroundColor = .clear // 避免和SwiftUI背景样式冲突
之后正常使用TextEditor即可:
TextEditor(text: $yourTextBinding) .frame(height: 100) .cornerRadius(14)
两种方法都能让TextEditor的输入文本和TextField保持一致的缩进效果。
内容的提问来源于stack exchange,提问作者Joseph
相关产品推荐
相关产品推荐

