Qiitaに書いたやつ

SwiftUIでTextViewを使う

iOSSwiftSwiftUI
2019年10月27日

SwiftUIではUIKitのUITextViewに対応する物がありません。 TextFieldにはLineLimitなるプロパティーも存在して複数業の入力ができそうですが、 2019年10月現在では、SwiftUIでT複数行入力できるViewを使うにはUITextViewをラップするしかなさそうです。

ここら辺も普通のUIViewRepresentableのお作法ですが、

struct TextView: UIViewRepresentable {
    @Binding var text: String

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
        textView.delegate = context.coordinator
        textView.isScrollEnabled = true
        textView.isEditable = true
        textView.isUserInteractionEnabled = true
        textView.backgroundColor = .green
        return textView
    }

    func updateUIView(_ textView: UITextView, context: Context) {
        textView.text = text
    }
}

extension TextView {
    final class Coordinator: NSObject, UITextViewDelegate {
        private var textView: TextView
        
        init(_ textView: TextView) {
            self.textView = textView
        }
        
        func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
            return true
        }
        
        func textViewDidChange(_ textView: UITextView) {
            self.textView.text = textView.text
        }
    }
}

stack overflow


余談: UITextViewの初期化部分をクロージャーで使う側で設定して見るのはどうなのか・・

struct TextView {
    @Binding var text: String
    let configure: (UITextView) -> ()
    
    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
        configure(textView)
        return textView
    }
}


TextView("text") { textView in 
    textView.isScrollEnabled = true
    textView.isEditable = true
    textView.isUserInteractionEnabled = true
}

同じタグの投稿

2020 churabou