在 macOS-SwiftUI 中禁用 TextEditor 的选择光标

问题描述

enter image description here

我可以使用以下代码禁用文本编辑器的选择和编辑:

TextEditor(text: self.$content)
    .allowsHitTesting(false)
    .disabled(true)

但这不会影响我的光标悬停在它里面时,这就是我想要的。有没有办法在禁用文本编辑器时将主光标保持在文本编辑器内,而不是选择光标?

我想要这个是因为我在 TextEditor 上方的 ZStack 中的其他视图总是有这个选择光标,这很烦人。

解决方法

您可以像这样使用 overlay 修饰符:

struct ContentView: View {
    
    @State private var string: String = "Hello,World!"
    @State private var disableStringSelection: Bool = Bool()
    
    var body: some View {
        
        VStack(spacing: 5.0) {
            
            Color.white
                .overlay(disableStringSelection ? Text(string).font(Font.body).padding(.leading,5.0) : nil,alignment: .topLeading)
                .overlay(disableStringSelection ? nil : TextEditor(text: $string).font(Font.body))
                .cornerRadius(10.0)

            Button(disableStringSelection ? "Enable Selection" : "Disable Selection") { disableStringSelection.toggle() }
            
        }
        .padding(5.0)

    }
    
}

enter image description here