Home>

I used UIViewRepresentable to wrap UITextView so that it can be used on Swift UI as shown below.

struct CustomTextView: UIViewRepresentable {
        func makeUIView (context: UIViewRepresentableContext<CustomTextView>)->UITextView {
            let textView = UITextView ()
            textView.backgroundColor = UIColor.clear
            textView.isScrollEnabled = false
            textView.textColor = UIColor.black
            textView.font = UIFont (name: "ArialMT", size: 20)
// textView.text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
            return textView
        }
        func updateUIView (_ uiView: UITextView, context: Context) {
        }
}

extension UIApplication {
    func closeKeyboard () {
        sendAction (#selector (UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}


The above is CustomTextView

I am using it as follows.

import SwiftUI
struct ContentView: View {
        var body: some View {
            ZStack {
            CustomTextView ()
                    .frame (width: 300, height: 300, alignment: .topLeading)
                    .border (Color.red, width: 1)
            } .onTapGesture {
                UIApplication.shared.closeKeyboard ()
            }
    }
}

If i enter a value from the keyboard with this, it will wrap in a frame with a red frame as shown below.

However, if you uncomment the above CustomTextView and put the character string directly in textView.text, the frame will be out of the frame as shown below.

I want to make the line break at the frame even if I enter characters directly.

If i understand, I would appreciate it if you could answer.