我需要显示图标从一个自定义字体在快速动态。图标格式类似:\u{code} example:\u{e054}。图标的动态值只包含代码,不包含\u{和},因此我需要一种构建字符串和连接内容的方法。
我让它工作了,我可以看到图标,但前提是我对它们进行了硬编码,所以它可以工作并显示图标:
// works and displays and icon something like ?
Text("\("\u{e054}")")
.font(.custom("custom-font", size: 30))但我需要动态显示它,下面的所有解决方案都不起作用,只显示栏文本,而不显示图标:
// doesn't work and displays \u{e054} instead of the icon
Text("\\u{\(icon_code)}")
.font(.custom("custom-font", size: 15))// also doesn't work and displays \u{e054} instead of the icon
Text( #\u{\#(icon_code)}#)
.font(.custom("custom-font", size: 15))发布于 2020-12-27 20:53:24
您可以轻松地创建字符串扩展,您可以通过将字符串转换为Int代码,然后将代码转换为unicode字符来处理该扩展
extension String {
var unicode: String {
guard let code = UInt32(self, radix: 16),
let scalar = Unicode.Scalar(code) else {
return ""
}
return "\(scalar)"
}
}可以像这样使用:
Text("e054".unicode)
.font(.custom("custom-font", size: 30))发布于 2020-12-27 20:16:21
我没有你的自定义字体,但是有了代码,我们可以使用Unicode.Scalar动态生成符号,就像下面的演示

var icon_code = 0xe054
var body: some View {
if let value = Unicode.Scalar(icon_code) {
Text(value.escaped(asASCII: false))
.font(.system(size: 60))
}
},它相当于硬编码。
Text("\u{e054}").font(.system(size: 60))如果原始输入是-a String,则使用转换器
var icon_code = "e054"
var body: some View {
if let code = Int(icon_code, radix: 16), let value = Unicode.Scalar(code) {
Text(value.escaped(asASCII: false))
.font(.system(size: 60))
}
}https://stackoverflow.com/questions/65465323
复制相似问题