今天写一下UITableView控件以及一个使用率非常高的视图控制器UITableViewController
简介
UITableView经常被用来展示一系列相似的信息,有点类似于平时所见的列表,它有两种形式,一种为UITableViewStylePlain,另一种为UITableViewStyleGrouped。其实二者没有多大差别,第二种只是在第一种的基础上按分组进行显示。我们平时常用第二种形式。
初始化
首先在控制器中声明一个UITableView的实例
@property (nonatomic, strong) UITableView *tableView;
初始化,指定位置和形式
self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStyleGrouped];
[self.view addSubview:self.tableView];
设置代理
UITableView需要两个代理,分别是UITableViewDelegate和UITableViewDataSource,他们分别用来处理UITableView的事件和为UITableView来提供数据。
我们把代理设置为当前的控制器
self.tableView.delegate = self;
self.tableView.dataSource = self;
1 . 该方法设置UITableView的块数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
该方法默认值为1,不一定必须实现,但是我比较喜欢实现它,因为符合UITableView的提供数据思路:块数-行数-每行数据
2 . 该方法设置UITableView每块的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
3 . 该方法返回UITableView每行的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
运行结果

完整代码
#import "ViewController.h"
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
//声明控件
@property (nonatomic, strong) UITableView *tableView;
//声明存储数据的数据结构
@property (nonatomic, strong) NSMutableArray *dataArray;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//初始化控件
self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStyleGrouped];
[self.view addSubview:self.tableView];
//设置代理
self.tableView.delegate = self;
self.tableView.dataSource = self;
//加载数据
[self loadData];
}
#pragma mark - 加载数据
- (void)loadData
{
for (int i = 0; i < 4; i++) {
NSMutableArray *arrayTemp = [NSMutableArray array];
for (int j = 0; j < 4; j++) {
NSString *stringTemp = [NSString stringWithFormat:@"第%d块 第%d行", i, j];
[arrayTemp addObject:stringTemp];
}
[self.dataArray addObject:arrayTemp];
}
}
#pragma mark - UITableViewDelegate & UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[self.dataArray objectAtIndex:section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cell_id = @"cell_id";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cell_id];
}
NSString *stringTemp = [[self.dataArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
cell.textLabel.text = stringTemp;
return cell;
}
#pragma mark - 懒加载
- (NSMutableArray *)dataArray
{
if (_dataArray == nil) {
self.dataArray = [NSMutableArray array];
}
return _dataArray;
}
总结
这样,UITableView的基本用法就说完了,下一次再说一下其他代理方法和UITableView的编辑和移动