1

SwiftUI にカスタム テキスト フィールドがあり、テキスト フィールドのコンテンツの量に応じて行数を調整します。アプリでは、ユーザーはテキスト フィールドを追加できるので、テキスト フィールドの高さと内容を配列に格納し、テキスト フィールドが追加されるたびに配列に追加します。

内のコードを削除するたびにupdateUIView()、アプリはスムーズに実行されますが、もちろん、テキスト フィールドは表示されませんが、以下のコードのようにコードを含めるたびに、CPU が 99% に急上昇し、アプリがフリーズします ( 1 つのテキスト フィールドのみ)。

なぜこれが起こっているのか、そしてそれに対する修正を知っている人はいますか?

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