harunaga
harunaga

Reputation: 385

SwiftUI Breaking line in UITextView wrapped by UIViewRepresentable

I'm struggling for breaking line in CustomUITextView. Please help...

I made CustomUITextView like 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) {  }
}

Then using it like this.

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

By keyboard input it works and lines are returned at red border.

But when I take away this comment in CustomUITextView

textView.text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"

It will be like this and doesn't break.

Is it possible to break line when I put Strings directly from code like above too ?

Does anyone know the solutions?

Upvotes: 2

Views: 984

Answers (1)

Asperi
Asperi

Reputation: 258541

You need to decrease compression resistance priority

demo

textView.font = UIFont(name: "ArialMT", size: 20)
textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
textView.text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
return textView

Upvotes: 2

Related Questions