macOS下SwiftUI TextEditor换行时文本闪烁UI故障求助
macOS SwiftUI TextEditor 单词换行闪烁问题
这是已知Bug吗?
是的,这是macOS平台SwiftUI TextEditor组件的已知渲染Bug。在多个SwiftUI版本(包括较新的beta版本)中,都有开发者反馈当文本触发自动换行、组件动态调整高度时,会出现文本整体闪烁的重绘异常,即使是你提供的这种极简实现也会触发。
可行的解决思路
- 固定组件高度:移除
.fixedSize(horizontal: false, vertical: true),改用明确的.frame(height: ...)固定TextEditor的高度,避免因内容变化频繁触发布局重绘。修改后的代码示例:
struct ContentView: View { @State private var text: String = "" var body: some View { VStack { TextEditor(text: $text) .frame(width: 300, height: 400) Spacer() } } }
- 封装原生NSTextView替代:通过
NSViewRepresentable封装原生的NSTextView,原生组件的渲染逻辑更稳定,能规避SwiftUI层的重绘闪烁问题。示例实现:
struct StableTextEditor: NSViewRepresentable { @Binding var text: String func makeNSView(context: Context) -> NSTextView { let textView = NSTextView() textView.isRichText = false textView.font = .systemFont(ofSize: 14) textView.delegate = context.coordinator return textView } func updateNSView(_ nsView: NSTextView, context: Context) { if nsView.string != text { nsView.string = text } } func makeCoordinator() -> Coordinator { Coordinator(self) } class Coordinator: NSObject, NSTextViewDelegate { let parent: StableTextEditor init(_ parent: StableTextEditor) { self.parent = parent } func textDidChange(_ notification: Notification) { guard let textView = notification.object as? NSTextView else { return } parent.text = textView.string } } } // 使用示例 struct ContentView: View { @State private var text: String = "" var body: some View { VStack { StableTextEditor(text: $text) .frame(width: 300) .fixedSize(horizontal: false, vertical: true) Spacer() } } }
- 关闭自动换行(仅限适配场景):如果业务场景允许,可关闭TextEditor的自动换行功能,从根源上避免换行触发的重绘,但这仅适合不需要自动换行的使用场景。
内容的提问来源于stack exchange,提问作者sarahaha
相关产品推荐
相关产品推荐

