UITableview-实现方式(二)

UITableview(一)今天讲解UITableview的另外一种实现方式 - 继承与UIViewController。当创建好一个项目之后会发现自带会有一个名叫ViewController的文档点击ViewController.h不难发现该文件直接继承的是UIViewController

UITableview(一)中说到要实现一个表视图必须实现UITableViewDataSource中到两个方法

1
2
3
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

首先在ViewController.h中添加UITableViewDelegate``UITableViewDataSource

为什么要添加UITableViewDelegate``UITableViewDataSource后续文章中会详细讲解。

之后在ViewController.m文件中添加两个必须实现的方法及相关代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}

return cell;
}

其次在 - (void)viewDidLoad;中还要注册cell当按照UITableview(一)中讲解的那样添加代码时

1
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];

是会报错的

意思是没有相关的tableView属性,因为UIViewController不继承UITableView所以不拥有UITableView中的属性。因此我们必须单独添加

首先初始化一个UITableView

1
UITableView *tableView = [[UITableView alloc] init];

初始化好之后就应该把UITableView视图添加到当前的视图中

1
[self.view addSubview:tableView];

之后还必须设置下tableViewframe固定下显示的位置,设置为填满整个屏幕

1
tableView.frame = [[UIScreen mainScreen] bounds];

而后就可以添加注册cell的代码了

1
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];

然而这并没有完事,还有两行最关键的代码需要添加

1
2
tableView.delegate = self;
tableView.dataSource = self;
  • 这两行代码是重中之重但却是最容易被忽视的

之后就可以运行了当然别忘了在AppDelegate.h文件中设置为rootViewController

最后祝大家双十一快~乐 – 想想你们真的快乐吗!!!😏