如何在没有固定宽度的情况下让文本包裹在

如何在没有固定宽度的情况下让文本包裹在

本文介绍了如何在没有固定宽度的情况下让文本包裹在 UILabel(通过 UIViewRepresentable)中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将 lineBreakMode 设置为 byWordWrapping 并将 numberOfLines 设置为 0 似乎还不够:

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

struct MyTextView: UIViewRepresentable {
    func makeUIView(context: Context) -> UILabel {
        let label = UILabel()
        label.lineBreakMode = .byWordWrapping
        label.numberOfLines = 0
        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) {
    }
}

struct MyTextView_Previews: PreviewProvider {
    static var previews: some View {
        MyTextView()
            .previewLayout(.fixed(width: 300, height: 200))
    }
}

无论我对 lineBreakMode 使用哪种设置,文本都不会换行.画布预览和实时预览都如下所示:

The text does not wrap, regardless of which setting I use for lineBreakMode. The canvas preview and live preview both look like this:

我得到的最接近的是设置 preferredMaxLayoutWidth,这确实会导致文本换行,但似乎没有一个值表示无论视图大小如何".

The closest I've gotten is setting preferredMaxLayoutWidth, which does cause the text to wrap, but there doesn't seem to be a value that means "whatever size the View is".

推荐答案

可能的解决方案是在 MyTextView 上将宽度声明为一个变量:

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) {
    }
}

然后使用 GeometryReader 找出有多少可用空间并将其传递给初始化器:

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)
        }
    }
}

这篇关于如何在没有固定宽度的情况下让文本包裹在 UILabel(通过 UIViewRepresentable)中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:00