在Swift中动态使用Font Awesome [英] Using Font Awesome dynamically in Swift

查看:87
本文介绍了在Swift中动态使用Font Awesome的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Swift中动态编码超棒的字符.我正在使用一个API,该API返回字符的代码(格式为f236),我想将它作为unicode注入到UILabel中.理想情况下,我想执行以下操作:

I am trying to dynamically encode font-awesome characters in Swift. I am using an API which returns the code for the character (in the format f236) and I want to inject this as unicode into a UILabel. Ideally I would like to do the following:

var iconCode: String? = jsonItem.valueForKey("icon") as? String
var unicodeIcon = "\u{\(iconCode)}"
label.text = "\(unicodeIcon) \(titleText)"

但是您显然无法做到这一点.有办法解决这个问题吗?

However you obviously can't do this. Is there a way around this problem?

推荐答案

@abdullah有一个很好的解决方案,但是这里有更多关于根本问题的信息,以防有人再次遇到它...

@abdullah has a good solution, but here's more about the root problem in case someone runs into it again...

由于Swift解析字符串转义码的顺序,您无法编写var unicodeIcon = "\u{\(iconCode)}"之类的内容.\u{xxxx}已经是一个转义码,并且您试图在其中嵌入另一个转义码(字符串插值) —解析器一次只能处理一个.

You can't write things like var unicodeIcon = "\u{\(iconCode)}" because of the order that Swift parses string escape codes in. \u{xxxx} is already one escape code, and you're trying to embed another escape code (string interpolation) within that — the parser can handle only one at a time.

相反,您需要一种更直接的方法来从十六进制Unicode标量值构造String(实际上是Character,因为您只有一个).这是这样做的方法(标量值是整数):

Instead, you need a more direct way to construct a String (actually, a Character, since you have only one) from a hexadecimal Unicode scalar value. Here's how to do that (with the scalar value as an integer):

let unicodeIcon = Character(UnicodeScalar(0x1f4a9))
label.text = "\(unicodeIcon) \(titleText)"

当然,您的字符代码在字符串中,因此您需要先从该字符串中解析出一个整数,然后才能将其传递给上面.这是UInt32上的一个快速扩展:

Of course, your character code is in a string, so you'll need to parse an integer out of that string before you can pass it to the above. Here's a quick extension on UInt32 for that:

extension UInt32 {
    init?(hexString: String) {
        let scanner = NSScanner(string: hexString)
        var hexInt = UInt32.min
        let success = scanner.scanHexInt(&hexInt)
        if success {
            self = hexInt
        } else {
            return nil
        }
    }
}

let unicodeIcon = Character(UnicodeScalar(UInt32(hexString: "1f4a9")!))
label.text = "\(unicodeIcon) \(titleText)"

这篇关于在Swift中动态使用Font Awesome的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆