Text("Hello World!")
.textSelection(.enabled)
This code will not allow to select only a word, e.g "Hello".
How to let it enable select a word?
Text("Hello World!")
.textSelection(.enabled)
This code will not allow to select only a word, e.g "Hello".
How to let it enable select a word?
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)
}
}
}