在尝试给武器添加区分新旧的Sparkles图标图标时发现简单的在文字后添加图案会非常不和谐,比如像这样:


 HStack(spacing: 5) {
    Text(guideItem.name)
        .strokeText(color: colorScheme == .dark ? Color(hex: "76b6ff").opacity(0.3) : .clear, lineWidth: 0.1)
        .shadow(color: colorScheme == .dark ? Color(hex: "A5CBF6").opacity(0.5) : .clear, radius: 4)
        .font(UIDevice.current.userInterfaceIdiom == .phone ? .callout : .title3)
        .foregroundColor(self.viewModel.getStatus(for: guideItem.id) ? Color.blue : Color.primary)

    if guideItem.special != nil {
        Image("special")
            .resizable()
            .renderingMode(.template)
            .aspectRatio(contentMode: .fit)
            .foregroundColor(.primary)
            .frame(width: 20, height: 20)
    }
}

可以看到这样的话文字和图案被HStack分成了两块,并且有种对齐的感觉,导致了和其他item视觉上的不平衡

虽然可以直接用类似下面这样转image为text再相加的方法,但图像大小和颜色都需要预先调整并且难以随着字体大小变化和适配不同屏幕大小的设备


    Text(LocalizedStringKey((guideItem.method != nil ? "item." : "") + guideItem.name), tableName: "Aeon")
    +
    Text(Image("special"))

要想把图片单纯的作为符号加入文字可以用两种方式作为字体和使用Symbol Image的方法把svg变成"符号",我们使用第二种,可以参考下面的文档
为你的 App 创建自定符号图像
获得自定符号模板后在矢量绘图软件将需要的图案编辑并验证再导入Xcode作为Symbol Image Set使用

之后就比较简单了,可以直接用Image("special") 使用添加的符号,注意一下细节就好了
比如在符号和文字之间添加空格个,但不要直接用" "这样的空格,不然很容易导致符号在字符比较长的时候符号换行到首尾,一个使用非换行空格避免符号
然后对于符号是否出现的判断也使用了'''guideItem.special != nil ? Image("special") : Image("transparentPlaceholder")'''这样的判断,因为不能直接用Text("")这样的文字和Image运算,也不能在里面对图片添加各种效果,所以使用了transparentPlaceholder这样1x1大小的透明图片作为替代


    HStack(spacing: 0) {
        Text(guideItem.name)
            + Text(guideItem.special != nil ? "\u{00A0}" : "") 
            + Text(guideItem.special != nil ? Image("special") : Image("transparentPlaceholder")) 
    }
    .strokeText(color: colorScheme == .dark ? Color(hex: "76b6ff").opacity(0.3) : .clear, lineWidth: 0.1)
    .shadow(color: colorScheme == .dark ? Color(hex: "A5CBF6").opacity(0.5) : .clear, radius: 4)
    .font(UIDevice.current.userInterfaceIdiom == .phone ? .callout : .title3)
    .foregroundColor(self.viewModel.getStatus(for: guideItem.id) ? Color.blue : Color.primary)

总之最后获得和文字适配同一个颜色的符号,并且需要的时候始终出现在文字最后无论是否换行,

并且会始终和文字保持一个字号和颜色,哪怕文字大小有变化也能完美适配,哪怕字号夸张到下面这样: