Auto-Correct not working on MacOS using NSTextView wrapped for SwiftUI

55 views Asked by At

The Problem

Working on a MacOS app using SwiftUI that uses a custom text editor, using NSViewRepresentable to wrap a NSTextView for customization needs. However, I can't get auto-correct spelling to work. Real-time spell checking works, but not auto-correction.

I created a fresh new project with an only basic editor to eliminate as many variables as possible, and it's still not working.

What am I missing?

The Code

import SwiftUI
import AppKit

struct MacOSTextView: NSViewRepresentable {
    @Binding var text: String
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    func makeNSView(context: Context) -> NSTextView {
        let textView = NSTextView()
        textView.delegate = context.coordinator
        textView.isAutomaticSpellingCorrectionEnabled = true
        textView.isContinuousSpellCheckingEnabled = true
        textView.allowsUndo = true
        textView.backgroundColor = NSColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1)
        textView.textColor = NSColor.labelColor
        return textView
    }
    
    func updateNSView(_ nsView: NSTextView, context: Context) {
        nsView.string = text
    }
    
    class Coordinator: NSObject, NSTextViewDelegate {
        var parent: MacOSTextView
        
        init(_ parent: MacOSTextView) {
            self.parent = parent
        }
        
        func textDidChange(_ notification: Notification) {
            guard let textView = notification.object as? NSTextView else { return }
            self.parent.text = textView.string
        }
    }
}

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

And then my ContentView:

import SwiftUI

struct ContentView: View {
    @State private var content: String = ""
    
    var body: some View {
        MacOSTextView(text: $content)
            .frame(minWidth: 200, minHeight: 200) // Adjust the size as needed
    }
}

What I've Tried:

  • System Settings > Keyboard > Input Sources > Correct Spelling Automatically is 'on'
  • In the above app, I right-click the text editor, choose "Spelling & Grammar" and check "Correct Spelling Automatically"
  • I've set textView.isContinuousSpellCheckingEnabled to false

I'm on MacOS Ventura 13.5

0

There are 0 answers