macOS|使用 TextEditor 添加文本编辑器

Placeholder
TextEditor 不支持 placeholder 参数。
可以通过自定义叠加(overlay)或 ZStack 的方式手动实现 placeholder 效果:
@State private var text: String = ""
var body: some View {
ZStack(alignment: .topLeading) {
if text.isEmpty {
Text("Enter your notes here...")
.foregroundColor(.gray)
.padding(.top, 8)
.padding(.leading, 5)
}
TextEditor(text: $text)
.padding(4)
}
.font(.body)
.frame(height: 150)
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(Color.gray.opacity(0.4), lineWidth: 1)
)
.padding()
}
.textEditorStyle() 修饰器
截止 iOS18,虽然提供了该修饰器,但还未提供具体的选项。
因此,目前暂时没用。
自定义字体大小、颜色
TextEditor() 支持使用 Text() 组件的修饰器,例如 .font
、.foregroundColor
。

在 macOS 上,Notion 编辑器的字体,接近于 title2
大小:
.font(.title2)
.fontWeight(.regular)

Craft 编辑器,接近于 title3
大小:

Bear 熊掌记使用的是自定义字体,大小接近于 title2
,但是更细、更浅:

禁用 TextEditor 滚动
TextEditor 默认会启动滚动功能。
例如,下面这个组件,高度超出 400 之后会自动启用滚动功能:
TextEditor(text: $text)
.frame(minHeight: 400)
使用 .scrollDisabled(true)
可禁用滚动。