富文本加图片 设置行高失效例子; 有效做法-label设置首行缩进 label上加imageview

本文介绍如何在 SwiftUI 开发中使用 NSAttributedString 来定制 UI 元素的样式,包括字体设置、图片插入及段落间距调整等技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

            let nsatrr = NSAttributedString.init(string:" " + (model.title ?? ""))

            let string = NSMutableAttributedString.init(attributedString: nsatrr)

            let font = UIFont.mediumSystemFont(ofSize: 14)

            

            let textAttachment = NSTextAttachment()

            textAttachment.image = UIImage.init(named: "Card_label_lto")

            let paddingTop = font.lineHeight - font.pointSize

            textAttachment.bounds = CGRect(x: 0, y: -paddingTop, width: 64, height: font.lineHeight)

            let textAttachmentString = NSAttributedString(attachment: textAttachment)

            string.insert(textAttachmentString, at: 0)

            // 间距

            let paragraphStyle = NSMutableParagraphStyle()

            paragraphStyle.minimumLineHeight = 20

            paragraphStyle.maximumLineHeight = 20

            string.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: string.length))

            

            nameLabel.attributedText = string