微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。