【问题标题】:UITextView Representable in SwiftUI not respecting bounds for width in ScrollViewUITextView 在 SwiftUI 中可表示不尊重 ScrollView 中的宽度界限
【发布时间】:2021-04-11 13:21:47
【问题描述】:

我想使用 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) {
        
    }
}

我想知道这是否与滚动视图有关。无论哪种方式,我都想知道是否有解决办法?我尝试将框架宽度设置为 geometry.size.width 但什么也没做。

【问题讨论】:

  • @Asperi 我看到了你的 UILabel 解决方案,但在这里不起作用。

标签: swift xcode swiftui uitextview


【解决方案1】:

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

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

【讨论】:

  • 这不起作用。这不是一个好的解决方案,因为我可能想在堆栈中添加其他元素,所以我不想局限于始终使用屏幕宽度。我希望它知道它的宽度范围,并在滚动视图中以无限的高度包装文本
  • 嗯,首先,你是对的,这对你的情况不起作用,我很抱歉。它仍然应该适用于大多数其他 UIRepresentables。其次,如果您使用的是 UIRepresentable,那么不幸的是,您会失去 SwiftUI 自动调整视图大小的部分功能。所以besically我理解你的想法,但我认为这是不可能的。我可能是错的。
猜你喜欢
  • 2021-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多