Swift中UITableView的用法(自定义UITableView和UITableViewCell)
一、自定义表视图(UITableView)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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import UIKit
class HomeTableView: UITableView, UITableViewDataSource, UITableViewDelegate {
//表视图的数据源:dataList
var dataList = [AnyObject]()
//单元格的标识符:homeCellId
let identify = "homeCellId"
//重写表视图初始化方法
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame:frame, style:style)
//调用初始化子视图方法
initSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//初始化表视图的子视图方法
func initSubviews () {
//设置数据源代理
dataSource = self;
//设置表视图代理
delegate = self;
//注册单元格class方式
registerClass(HomeCell.self, forCellReuseIdentifier: identify)
//设置表视图的分割线显示风格
separatorStyle = .None;
//注册单元格xib方式
//registerNib(UINib(nibName: "HomeCell", bundle: nil), forCellReuseIdentifier:identify)
}
//实现表视图返回组数代理方法:不实现默认为1
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
//实现表视图返回行数代理方法
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataList.count;
}
//实现表视图返回单元格代理方法
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//取单元格
let cell = tableView.dequeueReusableCellWithIdentifier(identify) as! HomeCell
//设置单元格的选中风格
cell.selectionStyle = .None;
cell.titleStr = dataList[indexPath.row] as? String
return cell
}
//选中单元格的代理方法
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("the indexpath row is \(indexPath.row)")
}
//返回单元格高度的代理方法
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80;
}
}
二、自定义单元格(UITableViewCell)
1 | import UIKit |