swift中tableview的使用和注意事项
2014-08-26 22:09
513 查看
今天使用swift写了个简单的tableView,语法和用法上跟oc没多大的区别。但是还是有一些细节的地方需要注意一下的。
先上代码
注意以下几点:
1,数据源方法,
2,cell的重用
初学经验,如有不妥,望大神指点
先上代码
import UIKit class 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的错误
初学经验,如有不妥,望大神指点
相关文章推荐
- 使用tableView时的3个注意事项(只适合初学者)
- 在tableView中,使用xib自定义view设置tableHeaderView时注意事项
- tableView 使用注意事项:一个tableView展示不同的cell时复用,以及数据更新
- 关于使用READ TABLE语句的几点注意事项
- iphone使用loadNibNamed载入view在内存中得注意事项
- 使用 OpenSessionInViewFilter 注意事项
- EGOImageView的使用方法及注意事项
- iphone使用loadNibNamed载入view在内存中得注意事项
- 使用TableAdapter的Update方法使用注意事项
- AutoCompleteTextView使用中的注意事项
- 关于使用READ TABLE语句的几点注意事项
- EGOImageView的使用方法及注意事项
- SurfaceView使用注意事项
- UIAlertView的使用注意事项
- iPhone开发笔记(20)EGOImageView的使用方法及注意事项
- 关于使用READ TABLE语句的几点注意事项...(原文来源于网络)
- iOS UIAlertView使用注意事项
- 关于使用READ TABLE语句的几点注意事项
- MFMessageComposeViewController使用的注意事项
- cocoa WebView使用注意事项