单击 SwiftUI 时选择 TextField 中的所有文本

时间:2021-05-12 10:47:49

标签: swift swiftui

我正在为 macOS 应用程序在 swiftui 中制作自定义网络浏览器。在文本字段内单击时如何选择所有文本?就像当您在地址栏内单击时使用 chrome 等网络浏览器一样。

import SwiftUI
import AppKit

   struct ContentView: View {

    var body: some View {
        TextField("Enter a URL", text: $site)
    
  }
}

1 个答案:

答案 0 :(得分:1)

SwiftUI 解决方案:

struct ContentView: View {
    var body: some View {
        TextField("Placeholder", text: .constant("This is text data"))
            .onReceive(NotificationCenter.default.publisher(for: UITextField.textDidBeginEditingNotification)) { obj in
                if let textField = obj.object as? UITextField {
                    textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument)
                }
            }
    }
}

注意:导入组合


使用 UIViewRepresentable 并包装 UITextField 并将 textField.selectedTextRange 属性与委托一起使用。

这是示例演示

struct HighlightTextField: UIViewRepresentable {
    
    @Binding var text: String
    
    func makeUIView(context: Context) -> UITextField {
        let textField = UITextField()
        textField.delegate = context.coordinator
        return textField
    }
    
    func updateUIView(_ textField: UITextField, context: Context) {
        textField.text = text
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(parent: self)
    }
    
    class Coordinator: NSObject, UITextFieldDelegate {
        var parent: HighlightTextField
        
        init(parent: HighlightTextField) {
            self.parent = parent
        }
        
        func textFieldDidBeginEditing(_ textField: UITextField) {
            textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument)
        }
    }
}



对于 macOS

struct HighlightTextField: NSViewRepresentable {
    
    @Binding var text: String
    
    func makeNSView(context: Context) -> CustomTextField {
        CustomTextField()
    }
    
    func updateNSView(_ textField: CustomTextField, context: Context) {
        textField.stringValue = text
    }
}

class CustomTextField: NSTextField {
    override func mouseDown(with event: NSEvent) {
        if let textEditor = currentEditor() {
            textEditor.selectAll(self)
        }
    }
}