问题描述
我正在使用Swift 3开发iOS应用.在此应用程序中,我列出了所有可用字体(已提供系统),但我也想列出所有可用字体.
I am developing an iOS app in Swift 3.In this app I am listing all available fonts (system provided) but I would like to list all available characters for them too.
例如,我正在使用Font Awesome,并且我希望用户能够从列表中选择任何字符/符号.我该怎么办?
For example I am using Font Awesome to and I want the user to be able to select any of the characters/symbols from a list. How can I do this?
这是我获取字体数组的方式.如何获得所选字体的所有字符的数组?
This is how I get an array of the fonts. How can I get an array of all characters for a selected font?
UIFont.familyNames.map({ UIFont.fontNames(forFamilyName: $0)}).reduce([]) { $0 + $1 }
推荐答案
对于每个UIFont,您都必须获取该字体的characterSet.例如,我先使用UIFont.
For each UIFont, you have to get characterSet of that font. For example, I take first UIFont.
let firsttFont = UIFont.familyNames.first
let first = UIFont(name: firsttFont!, size: 14)
let fontDescriptor = first!.fontDescriptor
let characterSet : NSCharacterSet = fontDescriptor.object(forKey: UIFontDescriptorCharacterSetAttribute) as! NSCharacterSet
然后,使用此扩展名获取该NSCharacterSet的所有字符:
Then, use this extension to get all characters of that NSCharacterSet:
extension NSCharacterSet {
var characters:[String] {
var chars = [String]()
for plane:UInt8 in 0...16 {
if self.hasMemberInPlane(plane) {
let p0 = UInt32(plane) << 16
let p1 = (UInt32(plane) + 1) << 16
for c:UTF32Char in p0..<p1 {
if self.longCharacterIsMember(c) {
var c1 = c.littleEndian
let s = NSString(bytes: &c1, length: 4, encoding: String.Encoding.utf32LittleEndian.rawValue)!
chars.append(String(s))
}
}
}
}
return chars
}
}
(参考: NSCharacterset的NSArray )
因此,最后,只需调用characterSet.characters
即可获取所有字符(在字符串中)
So, at last, just call characterSet.characters
to get all characters (in String)
这篇关于从字体获取所有可用字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!