swift中tableview的使用和注意事项
来源:互联网 发布:联通网络服务商电话 编辑:程序博客网 时间:2024/05/21 08:04
今天使用swift写了个简单的tableView,语法和用法上跟oc没多大的区别。但是还是有一些细节的地方需要注意一下的。
先上代码
import UIKitclass ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { var _tableView:UITableView? override func viewDidLoad() { super.viewDidLoad() _tableView=UITableView(frame: self.view.bounds, style:.Plain) self.view.addSubview(_tableView) _tableView!.delegate=self _tableView!.dataSource=self } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return 20; } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { var cell=tableView.dequeueReusableCellWithIdentifier("CellId") as? UITableViewCell if (cell==nil){ cell=UITableViewCell(style: .Default, reuseIdentifier: "CellId") } cell!.textLabel.text="\(indexPath.row)" return cell }}
注意以下几点:
1,数据源方法,
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int这两个方法是必须实现的,如果你不实现这两个方法,编译器就会报错。而不再是跟OC的时候一样,运行的时候才会报错所以,当你写完_tableView!.dataSource=self的时候,会出现报错,然后你在头部加班UITableViewDataSource,依然报错。当你实现了上面两个方法后,错误就会消失
2,cell的重用
var cell=tableView.dequeueReusableCellWithIdentifier("CellId") as? UITableViewCell 这里需要注意的一点是,后面强转成UITableViewCell的时候,在as后面带上个问号,因为在缓存池里不一定能找到可以重用的cell,不带问号就会引起cell为nil的错误
初学经验,如有不妥,望大神指点
0 0
- swift中tableview的使用和注意事项
- swift中tableview的使用
- Swift中tableView的建立与使用
- swift- tableView 的使用
- Swift中使用protocol的注意事项
- swift中switch的使用及注意事项
- swift tableView registerCell基于协议的实现和使用
- tableview中cell设置的注意事项
- Swift学习之--TableView的基本使用
- iOS TableView 使用(swift)
- swift-tableview使用
- iOS开发swift中tableView的条目点击的背景和文字颜色
- tableView的注意事项
- swift中tableView导航栏渐变和下拉变大效果
- qt中tableview的使用
- swift: Swift中static和class的使用
- bash中空格的使用和注意事项
- C++中全局变量的使用和注意事项
- CentOS 7.0编译安装Nginx1.6.0+MySQL5.6.19+PHP5.5.14[转]
- SSH证书登录方式(无密码验证登录)
- 数据库—SQL—数据库安全性
- 银行业务调度系统分析设计和Java代码的实现
- 详解互联网产品开发中的“快”字诀
- swift中tableview的使用和注意事项
- shell文本过滤编程(五):awk之printf
- 毕业三年差距是如何产生的
- ios7 Storyboard教程1
- GLabel GRect GOval GLine GCanvas GArc GImage GPolygon GCompound 未写完
- [cs105] nums.length&nums[i]
- ios7 Storyboard教程2
- LeetCode OJ算法题(六十六):Valid Number
- Android架构宏观理解和Android四个重要组件概念