UIViewRepresentable如何使UILabel压缩以适应内容大小?

问题描述 投票:0回答:1

我正在尝试在

UILabel
中制作
UIViewRepresentable
调整其高度以适应其内容(
NSAttributedString
)。我在这里阅读了很多问题,但仍然没有运气。

任何帮助将不胜感激!


左图显示了我当前的结果,右图显示了预期的结果

我失败的尝试(产生类似于左图的视图):

struct ContentView: View {
    let attributedText = NSAttributedString(string: "Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum")
    
    var body: some View {
        HStack {
            CustomUIViewRepresentable(attributedText: attributedText)
                .background(.yellow)
            Color.red
                .frame(width: 100, height: 100)
        }
    }
}

struct CustomUIViewRepresentable: UIViewRepresentable {
    let attributedText: NSAttributedString
    
    func makeUIView(context: Context) -> UIView {
        let label = UILabel()
        label.setContentCompressionResistancePriority(.sceneSizeStayPut, for: .horizontal)
        label.setContentCompressionResistancePriority(.sceneSizeStayPut, for: .vertical)
        label.numberOfLines = 0 // Can contains multiple lines of text
        label.lineBreakMode = .byWordWrapping
        label.attributedText = attributedText
        label.sizeToFit()
        return label
    }
    
    func updateUIView(_ uiView: UIViewType, context: Context) {}
}
swift uiview uikit uilabel uiviewrepresentable
1个回答
0
投票

正如您在评论中所说,您正在寻找

baselineOffset
和您的
AttributedString
。然而它不是
AttributedString
的属性,而是
Text
, baselineoffset(_:)

的函数

所以可能是:

private var attributedString: AttributedString {
    var attributedString = AttributedString("Lorem Ipsum")
    ...
    return attributedString
}

var body: some View {
    HStack {
        Text(attributedString)
            .baselineOffset(0) //<- here
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.