iOS15下SwiftUI中AttributedString设置paragraphStyle不生效问题咨询
问题原因
SwiftUI 中 Text 组件对 AttributedString 的属性解析逻辑和 UIKit 完全独立,你传入的 NSParagraphStyle 属于 UIKit 体系下的属性,目前 SwiftUI 的原生 Text 不会对该类段落属性做桥接识别,所以会出现其余属性生效、唯独段落样式不生效的情况。
解决方案
方案1:直接使用SwiftUI原生修饰符(最简单)
如果只是需要实现按字符换行的效果,不需要额外复杂富文本属性的场景,直接给Text加原生的lineBreakMode修饰符即可,不需要在AttributedString里设置段落样式:
Text("JKL Services Information Management") .font(.system(size: 15, weight: .semibold)) .foregroundColor(Constant.Theme.lightBlack) .lineBreakMode(.byCharWrapping) // 若需要不限行数换行可配合以下修饰符使用 .lineLimit(nil) .fixedSize(horizontal: false, vertical: true)
方案2:封装UILabel渲染富文本(兼容复杂富文本场景)
如果你确实需要通过AttributedString携带大量自定义属性,包括段落样式,可以用UIViewRepresentable封装UIKit的UILabel来渲染内容,UILabel可以正常识别所有UIKit体系下的富文本属性:
struct AttributedLabel: UIViewRepresentable { let attributedString: NSAttributedString let numberOfLines: Int = 0 func makeUIView(context: Context) -> UILabel { let label = UILabel() label.numberOfLines = numberOfLines return label } func updateUIView(_ uiView: UILabel, context: Context) { uiView.attributedText = attributedString } } // 使用示例 let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = .byCharWrapping let attributes: [NSAttributedString.Key: Any] = [ .paragraphStyle: paragraphStyle, .font: UIFont.systemFont(ofSize: 15, weight: .semibold), .foregroundColor: UIColor(Constant.Theme.lightBlack) ] let attributedStr = NSAttributedString(string: "JKL Services Information Management", attributes: attributes) // 页面内调用封装好的组件 AttributedLabel(attributedString: attributedStr)
补充说明
如果你的App最低支持版本为iOS16及以上,可以直接使用SwiftUI原生的AttributedString.ParagraphStyle类型设置段落属性,不需要依赖UIKit的相关类。
内容的提问来源于stack exchange,提问作者zhanqian
相关产品推荐
相关产品推荐

