我正在 Swift 3 中开发一个 iOS 应用程序。在这个应用程序中,我列出了所有可用的字体(系统提供),但我也想列出所有可用的字符。
例如,我使用 Font Awesome 并且我希望用户能够从列表中选择任何字符/符号。我怎样才能做到这一点?
这就是我获得字体数组的方式。如何获取所选字体的所有字符的数组?
UIFont.familyNames.map({ UIFont.fontNames(forFamilyName: $0)}).reduce([]) { $0 + $1 }
Run Code Online (Sandbox Code Playgroud)
对于每个 UIFont,您必须获得该字体的 characterSet。比如我先拿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
Run Code Online (Sandbox Code Playgroud)
然后,使用此扩展来获取该 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
}
}
Run Code Online (Sandbox Code Playgroud)
(参考:来自 NSCharacterset 的 NSArray)
所以,最后,只需调用characterSet.characters获取所有字符(在字符串中)
| 归档时间: |
|
| 查看次数: |
1198 次 |
| 最近记录: |