LoginSignup
18
11

More than 3 years have passed since last update.

SwiftUIでTextViewを使う

Last updated at Posted at 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
}
18
11
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
11