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! AppDelegate
        appdelegate.projectDetail = self
        self.tableView.delegate = self
        self.tableView.dataSource = self
        // remove the blank of the header of the table view,mind the height must be more than 0
        self.tableView.tableHeaderView = UIView(frame: CGRectMake(0,self.tableView.frame.size.width,0.01))
        // register the custom tableview cell
        var nib = UINib(nibName: "StationTableViewCell",bundle: nil)
        self.tableView.registerNib(nib,forCellReuseIdentifier: "cell")
    }

为了在Cell里面点击button可以实现页面跳转,我在界面刚初始化的时候,在AppDelegate里面实例化了一个当前ViewController的实例。如果对这个过程不了的,可以参见我的下一篇Blog,我会详细介绍一下如何实现。

接下来设置tableview的delegatedatasource代理

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

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

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

        var nib = UINib(nibName: "StationTableViewCell",forCellReuseIdentifier: "cell")

6.

实现两个代理方法

    // #MARK: tableview delegate
    func tableView(tableView: UITableView,heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(tableView: UITableView,didSelectRowAtIndexPath indexPath: NSIndexPath) {
        // To do 
    }
    
    // #MARK: tableview datasource
    func 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 tableview 
        var cell = tableView.dequeueReusableCellWithIdentifier("cell",forIndexPath: indexPath) as! StationTableViewCell
        return cell
    }

这几个代理方法就不多说了,很常用的。


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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...