3
    Text("Hello World!")
                    .textSelection(.enabled)

This code will not allow to select only a word, e.g "Hello".

What's this component? enter image description here

How to let it enable select a word?

Gank
  • 4,507
  • 4
  • 49
  • 45

1 Answers1

5

Since this feature is not yet natively available in SwiftUI you will have to create a UITextView() or UILabel() wrapper using UIViewRepresantable and then show that in your SwiftUI View.

First make your Wrapper.

import SwiftUI

struct TextViewWrapper: UIViewRepresentable {
    @Binding var text: String

    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
        textView.isEditable = false // Set to true if you want it to be editable
        textView.isSelectable = true // Enable text selection
        textView.font = UIFont.preferredFont(forTextStyle: .body)
        textView.delegate = context.coordinator
        return textView
    }

    func updateUIView(_ textView: UITextView, context: Context) {
        textView.text = text
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    class Coordinator: NSObject, UITextViewDelegate {
        var parent: TextViewWrapper

        init(_ parent: TextViewWrapper) {
            self.parent = parent
        }

        func textViewDidChange(_ textView: UITextView) {
            parent.text = textView.text
        }
    }
}

Then call it like this inside your main SwiftUI View.

struct ContentView: View {
    @State private var text = "Hello, world! SwiftUI is amazing."

    var body: some View {
        VStack {
            TextViewWrapper(text: $text)
                .padding()
                .border(Color.gray)
        }
    }
}

What are u mean not working? Look at the screenshot.

devdchaudhary
  • 467
  • 2
  • 13
  • Not work, your code only the whole text to lookup instead of select only one word to lookup, and doesn’t have translate button on the menu. Can you fix like the Twitter does? Thanks so much – Gank Jul 21 '23 at 12:31
  • 1
    I updated the answer with a screenshot, this is what you wanted right? Works for me. – devdchaudhary Jul 21 '23 at 17:06
  • Thanks, awesome! I am testing in scrollView: ScrollView { TextViewWrapper(text: "Your text here") .frame(height: 200) // Set an explicit height } I have to set the height, is there a way I don't need to set the height to make it visible? Thanks! – Gank Jul 22 '23 at 00:31
  • It's not always necessary to provide a frame, but in cases when SwiftUI is not able to automatically able to determine a frame for your UIKit view then yes you will have to give one explicitly. – devdchaudhary Jul 22 '23 at 09:23