问题
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?
回答1:
@abdullah has a good solution, but here's more about the root problem in case someone runs into it again...
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.
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)"
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)"
回答2:
If you are getting icon code as "fa-xxxx" then you could do this:
var iconCode = //Code from json...
label.text = "\(String.fontAwesomeIconWithName(iconCode)) \(titleText)"
I assume you have this method fontAwesomeIconWithName() in extension from font awesome and label.font is set as FontAwesome.
来源:https://stackoverflow.com/questions/29306722/using-font-awesome-dynamically-in-swift