这不是一个具体的答案。
struct ContentView: View {
let attributedString: NSAttributedString
var body: some View {
ScrollView {
LazyVStack(spacing: 10) {
RepresentedUILabelView(attributedText: attributedString)
.frame(maxHeight: 300)
.fixedSize(horizontal: false, vertical: true)
.background(Color.orange.opacity(0.5))
}
.padding()
}
}
}
struct RepresentedUILabelView: UIViewRepresentable {
typealias UIViewType = UILabel
var attributedText: NSAttributedString
func makeUIView(context: Context) -> UILabel {
let label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byTruncatingTail
label.textAlignment = .justified
label.allowsDefaultTighteningForTruncation = true
// Compression resistance is important to enable auto resizing of this view,
// that base on the SwiftUI layout.
// Especially when the SwiftUI frame modifier applied to this view.
label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
label.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
// Maybe this is not necessary.
label.clipsToBounds = true
return label
}
func updateUIView(_ uiView: UILabel, context: Context) {
print(#fileID, #function)
uiView.attributedText = attributedText
}
}
此外,如果您不希望提供最大高度。你可以设置
preferredMaxLayoutWidth
func updateUIView(_ uiView: UILabel, context: Context) {
uiView.attributedText = attributedText
uiView.preferredMaxLayoutWidth = 0.9 * UIScreen.main.bounds.width
}
func makeAttributedString(fromString s: String) -> NSAttributedString {
let content = NSMutableAttributedString(string: s)
let paraStyle = NSMutableParagraphStyle()
paraStyle.alignment = .justified
paraStyle.lineHeightMultiple = 1.25
paraStyle.lineBreakMode = .byTruncatingTail
paraStyle.hyphenationFactor = 1.0
content.addAttribute(.paragraphStyle,
value: paraStyle,
range: NSMakeRange(0, s.count))
// First letter/word
content.addAttributes([
.font : UIFont.systemFont(ofSize: 40, weight: .bold),
.expansion : 0,
.kern : -0.2
], range: NSMakeRange(0, 1))
return content
}
let coupleWords = "Hello, world!"
let multilineEN = """
Went to the woods because I wished to live deliberately, to front only the essential facts of life, and see if I could not learn what it had to teach, and not, when I came to die, discover that I had not lived. I did not wish to live what was not life, living is so dear! Nor did I wish to practise resignation, unless it was quite necessary?"
I went to the woods because I wished to live deliberately, to front only the essential facts of life, and see if I could.
I went to the woods because I wished to live deliberately, to front only the essential facts of life, and see if I could not learn what it had to teach, and not.
"""