Swift实现自定义TableViewCell

虽然SDK里面自带的TableViewCell功能已经算强大了,但是很多时候,我们还是需要自定义的Cell来满足我们自己的需求。最近研究了下如何用Swift实现自定义的TableViewCell,记录一下吧。

1.

点击左下角的加号,添加新的类

XCode6.3 做了一些小改动,整合了一下,点击File,然后进行下一步:

2.

这里可以给你自己的TableViewCell修改名字,记得把"Also create XIB file"前面的复选框选中

3.

设计你自己想要的XIB样式。AutoLayout很强大,多用一用就慢慢熟练了,可以省去很多代码量。

StationTableViewCell.swift文件基本不需要做大的变动

下面进行关键的步骤,在TableView中添加进刚才我们自定义的TableViewCell

4.

StoryBoard中我们设置好承载TableView的ViewController(ProjectDetail…Controller.swift)的各项属性

注意这里把tableview的style设置为Grouped,这样会在顶部出现一段空白,不过别担心,在接下来的代码里面我们会解决这个问题。

5.

ViewDidLoad:

override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view.let appdelegate = UIApplication.sharedApplication().delegate as! AppDelegateappdelegate.projectDetail = selfself.tableView.delegate = selfself.tableView.dataSource = self// remove the blank of the header of the table view, mind the height must be more than 0self.tableView.tableHeaderView = UIView(frame: CGRectMake(0, 0, self.tableView.frame.size.width, 0.01))// register the custom tableview cellvar nib = UINib(nibName: "StationTableViewCell", bundle: nil)self.tableView.registerNib(nib, forCellReuseIdentifier: "cell")}为了在Cell里面点击button可以实现页面的跳转,我在界面刚初始化的时候,在AppDelegate里面实例化了一个当前ViewController的实例。如果对这个过程不了的,可以参见我的下一篇Blog,我会详细介绍一下如何实现。

接下来设置tableview的delegate和datasource代理

然后就是刚才提到的,去除顶部的空白的代码了:

self.tableView.tableHeaderView = UIView(frame: CGRectMake(0, 0, self.tableView.frame.size.width, 0.01))注意这里frame的height不能是0,如果是0是没有效果的,必须是比0大一点,,但是我们把这个值设置的特别小,用肉眼看不出来,所以就变相达到了去除顶部空白的作用。所以我们设置成了0.01

接下来就是最关键的步骤了,初始化自定义的cell

var nib = UINib(nibName: "StationTableViewCell", bundle: nil)self.tableView.registerNib(nib, forCellReuseIdentifier: "cell")6.

实现两个代理方法

// #MARK: tableview delegatefunc tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {return 80}func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {// To do}// #MARK: tableview datasourcefunc numberOfSectionsInTableView(tableView: UITableView) -> Int {return 1}func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return 5}func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {// all the custom cell into the tableviewvar cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! StationTableViewCellreturn cell}这几个代理方法就不多说了,很常用的。

到这里所有的步骤都完成了,运行一下程序,看看自定义的是什么样子的吧。

为了一些琐事吵架,然后冷战,疯狂思念对方,最后和好。

Swift实现自定义TableViewCell

相关文章:

你感兴趣的文章:

标签云: