动态显示 Swift 中的自定义字体图标代码
Displaying custom font icon code in Swift dynamically
我需要使用 swift 中的自定义字体动态显示图标。
图标格式如下:\u{code}
例如:\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))
我没有你的自定义字体,但有代码我们可以使用 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))
}
}
您可以轻松创建字符串扩展,您可以通过将字符串转换为 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))
我需要使用 swift 中的自定义字体动态显示图标。
图标格式如下:\u{code}
例如:\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))
我没有你的自定义字体,但有代码我们可以使用 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))
}
}
您可以轻松创建字符串扩展,您可以通过将字符串转换为 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))