1

我在 SwiftUI 中有一个自定义文本字段,它根据文本字段中的内容量调整它的行数。在应用程序中,用户可以添加文本字段,因此我将文本字段的高度和内容存储在数组中,并在添加更多文本字段时附加到数组中。

每当我移除updateUIView().只有一个文本字段)。

有谁知道为什么会发生这种情况,以及任何解决方法?

struct CustomMultilineTF: UIViewRepresentable {
    
    @Binding var text: String
    @Binding var height: CGFloat
    var placeholder: String
    
    func makeCoordinator() -> Coordinator {
        return CustomMultilineTF.Coordinator(par: self)
    }
    
    func makeUIView(context: Context) -> UITextView {
        let view = UITextView()
        view.isEditable = true
        view.isScrollEnabled = true
        view.text = placeholder
        view.font = .systemFont(ofSize: 18)
        view.textColor = UIColor.gray
        view.delegate = context.coordinator
        view.backgroundColor = UIColor.gray.withAlphaComponent(0.05)
        return view
    }
    
    func updateUIView(_ uiView: UITextView, context: Context) {
        DispatchQueue.main.async {
            self.height = uiView.contentSize.height
        }
    }
    
    class Coordinator: NSObject, UITextViewDelegate {
        var parent: CustomMultilineTF
        init(par: CustomMultilineTF) {
            parent = par
        }
        
        func textViewDidBeginEditing(_ textView: UITextView) {
            if self.parent.text == "" {
                textView.text = ""
                textView.textColor = .black
            }
        }
        
        func textViewDidChange(_ textView: UITextView) {
            DispatchQueue.main.async {
                self.parent.height = textView.contentSize.height
                self.parent.text = textView.text
            }
        }
    }
}
4

1 回答 1

1

在您的updateUIView中,您将值设置为self.height,这是一个绑定。我的猜测是@Binding 连接到一个属性(另一个@Binding 或您周围视图上的@State)。因此,每当您为该@Binding 设置新值时,都会触发父视图的刷新。反过来,这最终会updateUIView再次调用,然后您就会陷入无限循环。

如何解决它可能取决于您对程序的架构需求。如果您可以不让父母知道高度,您可以通过让视图更新自己的高度来解决它。

如果它 != 旧值,您也可以尝试仅设置self.height为新值 - 这可能会使循环短路。但是,您最终可能会产生其他副作用。

于 2021-01-24T22:07:09.043 回答