3

我正在使用 SwiftUI 为 MacOS 开发基于 Python 的图形计算器。

https://github.com/snakajima/macplot

我正在使用 SwiftUI 的 TextEditor 作为 Python 代码的编辑器,但我无法弄清楚如何禁用智能引号(UITextInputTraits、smartQuotesType: UITextSmartQuotesType)。

        VStack {
            TextEditor(text: $pythonScript.script)
            HStack {
                Button(action: {
                    pythonScript.run(clear: settings.shouldClear)
                }, label: {
                    Text("Plot")
                })
                Toggle("Clear", isOn: $settings.shouldClear)
            }
            if let errorMsg = pythonScript.errorMsg {
                Text(errorMsg)
                    .foregroundColor(.pink)
            }
        }
4

2 回答 2

6

经过几次试验,我想出了以下解决方法。它依赖于 TextEditor 在 NSTextView 之上实现这一事实,并在整个应用程序中改变其行为。这很丑陋,但有效。

// HACK to work-around the smart quote issue
extension NSTextView {
    open override var frame: CGRect {
        didSet {
            self.isAutomaticQuoteSubstitutionEnabled = false
        }
    }
}
于 2021-03-20T19:16:51.050 回答
1

对于那些正在寻找 UIKit(iOS、iPadOS)而不是 AppKit(macOS)的答案的人,这对我来说使用了类似的方法。谢谢中本聪!

extension UITextView {
    open override var frame: CGRect {
        didSet {
            self.smartQuotesType = UITextSmartQuotesType.no
        }
    }
}

这具有相同的缺点,即您的应用程序中的所有文本字段都将丢失自动智能引号,但至少您可以在需要时控制它。

于 2021-07-18T20:41:35.880 回答