SwiftUI中submitLabel修饰符在TextEditor控件上不生效问题咨询
结论
submitLabel修饰符不支持作用于TextEditor控件,仅对TextField、SecureField等单行输入控件生效。
TextEditor属于多行文本输入组件,系统原生逻辑中return键的默认行为是输入换行符,不属于提交类交互,所以SwiftUI没有为TextEditor适配submitLabel的修饰能力,即使添加该修饰符也不会产生任何效果。
替代实现方案
如果需要修改TextEditor的return键样式,可以通过UIViewRepresentable桥接UITextView实现,示例代码如下:
import SwiftUI struct CustomTextEditor: UIViewRepresentable { @Binding var text: String var returnKeyType: UIReturnKeyType func makeUIView(context: Context) -> UITextView { let textView = UITextView() textView.returnKeyType = returnKeyType textView.delegate = context.coordinator return textView } func updateUIView(_ uiView: UITextView, context: Context) { uiView.text = text uiView.returnKeyType = returnKeyType } func makeCoordinator() -> Coordinator { Coordinator(text: $text) } class Coordinator: NSObject, UITextViewDelegate { @Binding var text: String init(text: Binding<String>) { _text = text } // 可选实现:监听return键点击,自定义点击逻辑 func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { // 示例:点击return键收起键盘 textView.resignFirstResponder() return false } return true } } } // 调用示例 struct ContentView: View { @State var text: String = "" var body: some View { Form { CustomTextEditor(text: $text, returnKeyType: .done) } } }
内容的提问来源于stack exchange,提问作者John Sorensen
相关产品推荐
相关产品推荐

