SwiftUI的TextEditor适用于多行文本输入,类似于 UITextView。
支持自动换行,可以显示较多的内容,非常适合用于编写长文本或备注。
用法:与字符串绑定,用于存储和实时更新用户输入。
基本用法
@State private var text = ""
TextEditor(text: $text)
和TextField的最大区别在于,TextField没有绑定数字的版本,只能绑定String。
常用修饰符
1、frame / padding / background。
TextEditor使用frame / padding / background 优化外观:
TextEditor(text: $text)
.frame(height: 200)
.padding()
.background(Color.gray.opacity(0.1))
.cornerRadius(8)
2、font:设置字体
.font(.body)
.font(.title3)
3、foregroundColor:设置文字颜色。
4、disableAutocorrection:关闭自动纠错。
.disableAutocorrection(true)
适合代码、命令、备注等场景。
5、autocapitalization:控制自动大写。
.autocapitalization(.none)
6、scrollContentBackground:iOS 16+,控制内部背景是否透明:
.scrollContentBackground(.hidden)
UIKit的UITextView默认有白色背景,如果使用自定义样式就需要隐藏默认背景。
7、focused / FocusState:控制键盘焦点。
@FocusState var focused: Bool
TextEditor(text: $text)
.focused($focused)
8、onChange:监听文字变化。
.onChange(of: text) { newText in
print("Changed:", newText)
}
适合存档、计数、自动保存等场景。
总结
TextEditor用于长文本输入,内容超过边界时会自动滚动、自动换行,支持选中、赋值、粘贴、撤销。
TextEditor本身不支持SwiftUI的行距设置,如果想要调整行距,需要使用UIKit包装器(UIViewRepresentable)。因为TextEditor底层是UITextView:
textView.typingAttributes[.paragraphStyle] = ...
相关文章
1、SwiftUI文本输入框TextField:https://fangjunyu.com/2025/11/17/swiftui%e6%96%87%e6%9c%ac%e8%be%93%e5%85%a5%e6%a1%86textfield/
