UITextView 可在 SwiftUI 中表示,不考虑 ScrollView 中的宽度界限

ali*_*ego 7 xcode uitextview swift swiftui

我想使用 SwiftUI 在 UITextView 中呈现文本。我正在使用 UIViewRepresentable 并在宽度超出滚动视图的边界时遇到问题。我希望是否将文本换行,但它只是在一根长线上继续,并且左侧和右侧不可见:

在此输入图像描述

这是我的代码:

struct ContentView: View {
    
    var messages = ["here is some long text to show the textView is not wrapping it's content"]
    
    var body: some View {
        GeometryReader { geometry in
            VStack(spacing: 0) {
                ScrollView(.vertical) {
                    ScrollViewReader { scrollView in
                        ZStack {
                            LazyVStack {
                                ForEach(messages, id: \.self) { message in
                                    TextView(text: message)
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

struct TextView: UIViewRepresentable {
    
    var text: String
     
    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
                
        textView.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
        textView.isScrollEnabled = false
        textView.backgroundColor = .clear
        textView.isEditable = false
        
        textView.clipsToBounds = true
        
        textView.isEditable = false
        
        textView.textContainerInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
        textView.backgroundColor = #colorLiteral(red: 0.03137254902, green: 0.4980392157, blue: 0.9960784314, alpha: 1)
        textView.textColor = UIColor.white

        textView.text = text

        return textView
    }
 
    func updateUIView(_ uiView: UITextView, context: Context) {
        
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道这是否与滚动视图有关。不管怎样,我想知道是否有解决办法?我尝试将框架宽度设置为geometry.size.width,但这没有任何作用。

Mah*_* BM 0

发生这种情况是因为您使用的是 UIRepresentable 视图。有几种解决方案,其中最简单的是.frame()在 SwiftUI 视图中的 UIRepresentable 视图之上使用显式。

例如.frame(width: UIScreen.main.bounds.width),它只能延伸到屏幕的宽度。

  • 这是行不通的。这不是一个好的解决方案,因为我可能想在堆栈中添加其他元素,所以我不想局限于始终使用屏幕宽度。我希望它知道它的宽度界限并以无限高度换行文本,因为它位于滚动视图中 (2认同)