UILabel word wrapping in SwiftUI

Hello!


I'm trying to use a UILabel in a tree of SwiftUI views, creating a View Struct that conforms to UIViewRepresentable. The reason for using UILabel instead of the native SwiftUI Text() view is that I would like to display an NSAttributedString.


The UILabel renders in the SwiftUI view, however the words do not wrap to become multi-line on the screen. Instead, the text just chops off at the trailing edge. The same UILabel settings in a purely UIKit based ViewController setup wrap correctly, for comparison. Providing a plain string to UILabel.text or an attributed string to UILabel.attributedText yields the same non-wrapping results.


I am just wondering if anyone has got this to work, or knows where I might be going wrong? Here is the view struct:


struct UIKitLabelView : UIViewRepresentable {

    typealias UIViewType = UILabel

    func makeUIView(context: UIViewRepresentableContext<UIKitLabelView>) -> UILabel {
        
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.lineBreakMode = .byWordWrapping
        label.numberOfLines = 0
        label.text = "a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20"
        return label
        
        // The text above should easily wrap on any character boundary, but is just chopped off at the "1" which is the character right before the edge of the device's screen.
        
    }
    
    func updateUIView(_ uiView: UILabel, context: UIViewRepresentableContext<UIKitLabelView>) {
        
    }
    
}

Here is the SwiftUI view hierarchy that embeds the UIKitLabelView at line 13:


struct MyView: View {
    
    var body: some View {
        
        ScrollView {
            
            VStack(alignment: .leading, spacing: nil) {

                Text("Title")
                
                Divider()
                
                UIKitLabelView()
                
                Spacer()

                .navigationBarTitle("My View")

            }
            .padding(20)
        }

    }
}


Thanks in advance for your help!

I've been stuck on the same problem for a while now. You haven't found an answer yet, have you?

Someone on StackOverflow helped. Their answer works for me!

Try using .fixedSize(horizontal: false, vertical: true)
UILabel word wrapping in SwiftUI
 
 
Q