如何让 SwiftUI 的 Text 支持长按单词和启用查看菜单的弹出警告?

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

这段代码将不允许仅选择一个单词,例如"Hello"。
这个组件是什么?enter image description here 如何使其能够选择一个单词?

你还不能用SwiftUI做到这一点。寻找UIKit中的等效方法来实现它。 - Alexnnd
1
@Alexnnd 你能告诉我如何使用UIKit来完成吗? - Gank
1
@Alexnnd 你能告诉我如何使用UIKit来完成吗? - Gank
1
@Alexnnd 你能告诉我如何使用UIKit来完成吗? - undefined
我试过了,但是没有成功 @Alexnnd - Gank
显示剩余4条评论
1个回答

5

由于此功能在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
        }
    }
}

然后在您的主要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)
        }
    }
}

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


1
我用一张截图更新了答案,这就是你想要的对吧? 对我来说没问题。 - lemonator21
1
我用截图更新了答案,这就是你想要的对吧? 对我来说没问题。 - devdchaudhary
谢谢,太棒了!我正在scrollView中进行测试: ScrollView { TextViewWrapper(text: "在这里输入你的文本") .frame(height: 200) // 设置一个明确的高度 } 我必须设置高度,有没有办法不需要设置高度就能让它可见?谢谢! - Gank
谢谢,太棒了!我正在scrollView中进行测试: ScrollView { TextViewWrapper(text: "在这里输入您的文本") .frame(height: 200) // 设置一个明确的高度 } 我必须设置高度,有没有办法不需要设置高度就能让它可见?谢谢! - Gank
并不总是需要提供一个框架,但在 SwiftUI 无法自动确定 UIKit 视图的框架时,您需要明确地给出一个框架。 - lemonator21
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接