You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI如何在多行文本右侧嵌入Assets自定义图片(非HStack实现)

解决多行文本末尾嵌入自定义图片的问题

要实现自定义图片跟随多行文本末尾(无需HStack),可以通过AttributedString将图片作为文本附件嵌入,完美适配文本行高,避免直接用Text(Image("info"))导致的尺寸错位问题。

实现步骤与代码示例

import SwiftUI

struct ContentView: View {
    var body: some View {
        // 准备基础文本
        let baseText = "这是一段可能会换行的多行文本,需要在末尾附加自定义图片,无论文本跨多少行,图片都要显示在最后一行的末尾位置。"
        
        // 加载并处理自定义图片
        guard let image = UIImage(named: "info") else {
            return Text(baseText)
        }
        // 调整图片尺寸,匹配文本行高(可根据需求修改scale值)
        let scaledImage = image.scalePreservingAspectRatio(targetHeight: 16)
        
        // 创建文本附件并转换为AttributedString
        let attachment = NSTextAttachment()
        attachment.image = scaledImage
        // 设置附件与文本的垂直偏移,确保对齐
        attachment.bounds = CGRect(x: 0, y: -2, width: scaledImage.size.width, height: scaledImage.size.height)
        
        let attachmentString = NSAttributedString(attachment: attachment)
        var attributedText = NSMutableAttributedString(string: baseText)
        attributedText.append(attachmentString)
        
        // 用SwiftUI的Text显示带附件的富文本
        Text(AttributedString(attributedText))
            .padding()
    }
}

// 扩展UIImage,方便按比例缩放图片
extension UIImage {
    func scalePreservingAspectRatio(targetHeight: CGFloat) -> UIImage {
        let widthRatio = targetHeight / size.height
        let newWidth = size.width * widthRatio
        let newSize = CGSize(width: newWidth, height: targetHeight)
        let renderer = UIGraphicsImageRenderer(size: newSize)
        
        return renderer.image { _ in
            self.draw(in: CGRect(origin: .zero, size: newSize))
        }
    }
}

关键说明

  • 通过NSTextAttachment将自定义图片转为文本附件,能让图片完全融入文本流,自动跟随最后一行末尾,无需依赖HStack布局。
  • 利用图片缩放方法scalePreservingAspectRatio,可以精准控制图片尺寸,使其匹配文本行高,避免出现图片过大或错位的问题。
  • 调整attachment.bounds的y值,可微调图片与文本的垂直对齐效果,确保视觉上更协调。

内容的提问来源于stack exchange,提问作者svranaw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 18:42:39