在Swift中动态使用Font Awesome

时间:2015-03-27 17:32:28

标签: swift font-awesome

我试图在Swift中动态编码字体真棒字符。我正在使用一个返回字符代码的API(格式为f236),我希望将其作为unicode注入UILabel。理想情况下,我想做以下事情:

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

但是你显然无法做到这一点。有没有解决这个问题的方法?

4 个答案:

答案 0 :(得分:5)

@abdullah有一个很好的解决方案,但是如果有人再遇到它,那么更多关于根本问题......

由于Swift解析字符串转义码的顺序,你不能写var unicodeIcon = "\u{\(iconCode)}"之类的东西。\u{xxxx}已经是一个转义码,你试图嵌入另一个转义码(字符串)插值) - 解析器一次只能处理一个。

相反,您需要一种更直接的方法来构造一个String(实际上,Character,因为您只有一个)来自十六进制Unicode标量值。以下是如何做到这一点(标量值为整数):

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

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

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)"

答案 1 :(得分:1)

如果你得到的图标代码是" fa-xxxx"然后你可以这样做:

var iconCode = //Code from json...
label.text = "\(String.fontAwesomeIconWithName(iconCode)) \(titleText)"

我假设您在font awesome的扩展名中使用了此方法fontAwesomeIconWithName(),并将label.font设置为FontAwesome。

答案 2 :(得分:0)

将iconHex字符串转换为十进制,然后将十进制转换为UnicodeScaler,然后转换为字符。最后使用字符串插值获得结果:

let iconStringHex = "f236"
let iconDecimal = Int(iconStringHex, radix: 16)!

let unicodeIcon = Character(UnicodeScalar(iconDecimal)!)
label.text = "\(unicodeIcon)"

答案 3 :(得分:0)

import Foundation
import FontAwesome_swift

class FontAwesomeConverter {
    public static func image(fromChar iconCode: String,
                         color: UIColor) -> UIImage {
    let label = UILabel(frame: .zero)
    label.textColor = color
    label.font = UIFont.fontAwesome(ofSize: 20, style: .solid)

    let iconDecimal = Int(iconCode, radix: 16)!
    let unicodeIcon = Character(UnicodeScalar(iconDecimal)!)
    label.text = "\(unicodeIcon)"
    label.sizeToFit()

    let renderer = UIGraphicsImageRenderer(size: label.frame.size)
    let image = renderer.image(actions: { context in
        label.layer.render(in: context.cgContext)
    })
    return image
   }
 }

extension UILabel {
// MARK:  set center alignment
   public func setFontAwesomeIcon(fromChar iconCode: String,
                        color: UIColor) {
    self.font = UIFont.fontAwesome(ofSize: 30, style: .solid)
    self.textColor = color

    let iconDecimal = Int(iconCode, radix: 16)!
    let unicodeIcon = Character(UnicodeScalar(iconDecimal)!)
    self.text = "\(unicodeIcon)"
    self.sizeToFit()
  }
}

用法:

//对于ImageView图像

imageView_MainMenu.image = FontAwesomeConverter.image(fromChar: "f085", color: .white)

//对于标签

label_MainMenu.setFontAwesomeIcon(fromChar: "f085", color: .white)