How can I get text to wrap in a UILabel (via UIViewRepresentable) without having a fixed width?

后端 未结 3 1288
闹比i
闹比i 2020-12-02 00:14

Setting lineBreakMode to byWordWrapping and set numberOfLines to 0 does not seem to be sufficient:

struct MyTextView: UIViewRepresentable {
    func makeUIVi         


        
3条回答
  •  没有蜡笔的小新
    2020-12-02 00:53

    Possible solution is to declare the width as a variable on MyTextView:

    struct MyTextView: UIViewRepresentable {
    
        var width: CGFloat
    
        func makeUIView(context: Context) -> UILabel {
            let label = UILabel()
            label.lineBreakMode = .byWordWrapping
            label.numberOfLines = 0
            label.preferredMaxLayoutWidth = width
            label.text = "Here's a lot of text for you to display. It won't fit on the screen."
            return label
        }
    
        func updateUIView(_ view: UILabel, context: Context) {
        }
    }
    

    and then use GeometryReader to findout how much space there is avaible and pass it into the intializer:

    struct ExampleView: View {
    
        var body: some View {
            GeometryReader { geometry in
                MyTextView(width: geometry.size.width)
            }
        }
    }
    

提交回复
热议问题