SWIFT 中的 UIFont 扩展
UIFont extension in SWIFT
我正在尝试为 Swift 书面项目编写 UIFont 扩展。我收到错误 'AnyObject is not convertible to String'。我该如何解决这个问题。这是我所做的
func listAllFontsOnSystem(){
var familyNames = NSArray(array: UIFont.familyNames())
var fontNames = []
var indFamily, indFont : NSInteger
for (indFamily = 0 ; indFamily<familyNames.count; ++indFamily){
//Error on next line
fontNames = NSArray(array: UIFont.fontNamesForFamilyName(familyNames .objectAtIndex(indFamily)))
for indFont = 0; indFont<fontNames.count; ++indFont{
print(fontNames.objectAtIndex(indFont))
}
}
}
试试这个代码。 UIFont.familyNames
returns AnyObject
的数组即 [AnyObject]
。它必须转换为字符串数组,即 [String]
.
func listAllFontsOnSystem(){
var familyNames = UIFont.familyNames() as [String]
for familyName in familyNames {
let fontNames = UIFont.fontNamesForFamilyName(familyName) as [String]
for fontName in fontNames {
println(fontName)
}
}
}
UIFont.fontNamesForFamilyName(familyNames.objectAtIndex(indFamily))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
objectAtIndex,是 Objective-C 方法 returns id
,returns Swift 中的 AnyObject
实例,而不是字符串。您可以 "cast" 将其转换为 String。
fontNames = NSArray(array: UIFont.fontNamesForFamilyName(
familyNames.objectAtIndex(indFamily) as String))
这是 Swift 少 Objective-C 的版本的样子:
class func listAllFontsOnSystem2(){
let familyNames = UIFont.familyNames() as [String]
for familyName in familyNames {
let fontNames = UIFont.fontNamesForFamilyName(familyName) as [String]
for fontName in fontNames {
println(fontName)
}
}
}
我正在尝试为 Swift 书面项目编写 UIFont 扩展。我收到错误 'AnyObject is not convertible to String'。我该如何解决这个问题。这是我所做的
func listAllFontsOnSystem(){
var familyNames = NSArray(array: UIFont.familyNames())
var fontNames = []
var indFamily, indFont : NSInteger
for (indFamily = 0 ; indFamily<familyNames.count; ++indFamily){
//Error on next line
fontNames = NSArray(array: UIFont.fontNamesForFamilyName(familyNames .objectAtIndex(indFamily)))
for indFont = 0; indFont<fontNames.count; ++indFont{
print(fontNames.objectAtIndex(indFont))
}
}
}
试试这个代码。 UIFont.familyNames
returns AnyObject
的数组即 [AnyObject]
。它必须转换为字符串数组,即 [String]
.
func listAllFontsOnSystem(){
var familyNames = UIFont.familyNames() as [String]
for familyName in familyNames {
let fontNames = UIFont.fontNamesForFamilyName(familyName) as [String]
for fontName in fontNames {
println(fontName)
}
}
}
UIFont.fontNamesForFamilyName(familyNames.objectAtIndex(indFamily))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
objectAtIndex,是 Objective-C 方法 returns id
,returns Swift 中的 AnyObject
实例,而不是字符串。您可以 "cast" 将其转换为 String。
fontNames = NSArray(array: UIFont.fontNamesForFamilyName(
familyNames.objectAtIndex(indFamily) as String))
这是 Swift 少 Objective-C 的版本的样子:
class func listAllFontsOnSystem2(){
let familyNames = UIFont.familyNames() as [String]
for familyName in familyNames {
let fontNames = UIFont.fontNamesForFamilyName(familyName) as [String]
for fontName in fontNames {
println(fontName)
}
}
}