由于此功能在SwiftUI中尚不可用,您将需要使用UIViewRepresentable
创建一个UITextView()
或UILabel()
的包装器,然后在您的SwiftUI视图中显示它。
首先创建您的包装器。
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
}
}
}
struct ContentView: View {
@State private var text = "Hello, world! SwiftUI is amazing."
var body: some View {
VStack {
TextViewWrapper(text: $text)
.padding()
.border(Color.gray)
}
}
}