SwiftUI实现ChatGPT风格可扩展TextEditor的技术求助
复刻ChatGPT iOS应用的可扩展TextEditor组件
我是一名正在学习SwiftUI的Flutter开发者,目前开发一款ChatGPT克隆应用,想要实现ChatGPT iOS应用里的可扩展文本编辑器组件。试过很多文章里的方案,感觉都是临时变通方法。最接近的是用TextField实现,代码如下:
TextField("What's up?", text: $text, axis: .vertical) .lineLimit(1...5)
但这个TextField没法按Enter键换行,而这正是TextEditor的核心作用。想要实现的效果如下:
实现方案
可以通过TextEditor结合frame和辅助视图来实现匹配的效果,既支持Enter换行,又能控制高度范围:
struct ExpandingTextEditor: View { @Binding var text: String // 定义最小/最大高度,可根据需求调整 private let minHeight: CGFloat = 44 private let maxHeight: CGFloat = 120 var body: some View { TextEditor(text: $text) // 限制高度范围,超出最大高度后会自动滚动 .frame(minHeight: minHeight, maxHeight: maxHeight) .scrollDismissesKeyboard(.interactively) // 自定义占位符,弥补TextEditor原生无占位符的缺陷 .background( ZStack(alignment: .topLeading) { if text.isEmpty { Text("输入你的问题...") .foregroundColor(.secondary) .padding(.horizontal, 8) .padding(.vertical, 12) } Color.clear } ) // 还原ChatGPT输入框的视觉样式 .cornerRadius(12) .overlay( RoundedRectangle(cornerRadius: 12) .stroke(Color.gray.opacity(0.3), lineWidth: 1) ) } } // 调用示例 struct ContentView: View { @State private var inputText = "" var body: some View { VStack { Spacer() ExpandingTextEditor(text: $inputText) .padding(.horizontal) } .padding(.bottom, 20) } }
关键细节
- 用
TextEditor原生支持Enter换行,解决TextField的核心缺陷 - 通过
frame(minHeight:maxHeight:)控制输入框的伸缩范围,超过最大高度后自动开启滚动 - 自定义占位符视图,实现和ChatGPT一致的空状态提示
- 添加边框和圆角,还原原生应用的视觉风格
内容的提问来源于stack exchange,提问作者Rehmat Singh Gill
相关产品推荐
相关产品推荐

