最近在学习用swift写东西,这里用swift写的一个关于tableView的一个小实例,希望可以帮到和我一样在学习swift道路上不断爬坑,勇往直前的小伙伴们。文章里面加的详细的注释说明,同时欢迎朋友在评论里面提意见,我会继续努力的。
下面是代码部分:
//建立tableViewvar tableView = UITableView()
let cellID = "cellID"
//var tableData = (titles:[String], values:[String])?
//建立数据数组
var tableData = ["宝宝0","宝宝1","宝宝2","宝宝3","宝宝4","宝宝5","宝宝6","宝宝7","宝宝8","宝宝9","宝宝10","宝宝11","宝宝12","宝宝13","宝宝14","宝宝15","宝宝16","宝宝17","宝宝18","宝宝19","宝宝20","宝宝21","宝宝22","宝宝23","宝宝24","宝宝25","宝宝26","宝宝27","宝宝28","宝宝29","宝宝30","宝宝31"]
override func viewDidLoad() {super.viewDidLoad()
self.title = "tableView"
self.view.backgroundColor = UIColor.blueColor()
//设置tableView的frame
self.tableView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
//当需要加载单独cell类的时候需要将cell注册之后才能加载到工程里面去
//self.tableView.registerNib(nib, forCellReuseIdentifier: cellID)
//tableView的两个代理方法
self.tableView.dataSource = self
self.view.addSubview(self.tableView)
//刷新表
self.showData()
} //刷新表
func showData() {
self.tableView.reloadData()
}
//内存警告时调用
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()}
}
//talbeView 的两个代理方法的实现,其实这两个代理还能加到class声明的后面,代理方法的时候和OC里面的实现是一样的
extension TestViewController:UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// let cell:SwiftCell = tableView.dequeueReusableCellWithIdentifier("SwiftCell")
// as! SwiftCell
// let item = tableData[indexPath.row]
// cell.customLabel.text = item
// //cell.customImage.image = UIImage(named:item["image"]!)
// return cell
let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle,reuseIdentifier: cellID)
cell.textLabel?.text = tableData[indexPath.row]
return cell
}
}
extension TestViewController:UITableViewDelegate{
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
print(tableData[indexPath.row])
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return 50
}