SwiftTableView

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

代码来源 cocoachina推荐源码 26日

上面这些是一些基本的设置,然后提前补充几个知识点!

类后面的!作用是强制类型转换

NSCoder是一个抽象类,是字节流的抽象类,我们可以把数据写入一个coder也可以从coder中读出数据!

as也可以类型为类型转换

Swift中sort函数有两种用法,在编译器中输入sort查看帮助文档有相信解释!

建议观看Swift language 函数章节

import UIKitclassViewController: UITableViewController {

var familyNames : Array<String> =[]

var fonts : Dictionary<String, String[]> =[:]

init(coder aDecoder: NSCoder!)

{

super.init(coder: aDecoder)

let unsortedFamilyNames= UIFont.familyNames()asString[]

familyNames=sort(unsortedFamilyNames)forfamilyNameinfamilyNames

{

let unsortedFontNames= UIFont.fontNamesForFamilyName(familyName)asString[]

fonts[familyName]=sortFontNames(unsortedFontNames)

}

}overridefunc numberOfSectionsInTableView(tableView: UITableView!) ->Int

{returncountElements(familyNames)

}overridefunc tableView(tableView: UITableView!, numberOfRowsInSection section: Int) ->Int

{

let key=familyNames[section]

let array=fonts[key]returnarray!.count

}overridefunc tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{

let cell= tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)asUITableViewCell

let key=familyNames[indexPath.section]

let array=fonts[key]

let fontName= array![indexPath.row]

cell.textLabel.text=fontName

cell.textLabel.font=UIFont(name:fontName, size: UIFont.systemFontSize())returncell

}overridefunc tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) ->CGFloat

{

let key=familyNames[indexPath.section]

let array=fonts[key]

let fontName= array![indexPath.row]

let label= UILabel(frame: CGRectMake(0,0,280,200))

label.text=fontName

label.font=UIFont(name: fontName, size: UIFont.systemFontSize())

label.sizeToFit()returnmax(label.font.lineHeight + label.font.ascender + -label.font.descender,44)

}/*This function is necessary because fonts shouldn't always be sorted alphabetically.

For example, ArialMT should come before Arial-BoldItalicMT,

but if we sort alphabetically, it doesn't.*//*这个函数是必要的,因为字体不总是按字母顺序排序。

例如,ArialMT应该Arial-BoldItalicMT之前,

但是如果我们按字母顺序排序,ArialMT就不会在Arial-BoldItalicMT之前。*/func sortFontNames(array: String[])->String[]

{returnsort(array, { (s1: String, s2: String) -> Boolin//if s1 doesn't contain a hyphen, it should appear before s2let count1 = countElements(s1.componentsSeparatedByString("-"))ifcount1 ==1{returntrue}//if s2 doesn't contain a hyphen, it should appear before s1let count2 = countElements(s2.componentsSeparatedByString("-"))ifcount2 ==1{returnfalse}//otherwise, a normal string compare will be finereturns1 >s2

})

}

}

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航