Text("Hello World!")
.textSelection(.enabled)
Run Code Online (Sandbox Code Playgroud)
此代码不允许仅选择一个单词,例如“Hello”。
如何让它启用选择单词?
由于此功能在 SwiftUI 中尚未原生提供,您必须使用创建一个UITextView()
或UILabel()
包装器UIViewRepresantable
,然后在 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在主 SwiftUI 视图中这样调用它。
struct ContentView: View {
@State private var text = "Hello, world! SwiftUI is amazing."
var body: some View {
VStack {
TextViewWrapper(text: $text)
.padding()
.border(Color.gray)
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
339 次 |
最近记录: |