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的delegate和datasource代理 然后就是刚才提到的,去除顶部的空白的代码了: 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 } 这几个代理方法就不多说了,很常用的。
到这里所有的步骤都完成了,运行一下程序,看看自定义的是什么样子的吧。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- .net – 序列化为XML时防止可空值类型
- DB2和 Oracle的并发控制(锁)的比较
- Oracle客户端安装配置
- C语言中sizeof()与strlen()函数的使用入门及对比
- Qt和SQLite无法处理’NULL’值或者我做错了什么?
- 尝试使用swift mailer,gmail smtp,php发送邮件
- ruby-on-rails – 显示RAILS_ROOT索引的Ruby on Rails应用程
- ruby-on-rails-3 – respond_with正在询问错误位置
- Oracle重做日志文件组-新增、删除
- iphone – 在Storyboard中隐藏一个ViewController的Navigat