表示图可谓是iOS开发中最常用的一个控件,没有之一。深入学习之后你会发现他有很多强大的功能,几乎可以用tableView实现所有的UI界面。
//表示图的创建
self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
//设置代理
self.tableView.delegate = self;
self.tableView.dataSource = self;
//设置背景颜色
self.tableView.backgroundColor = [UIColor redColor];
//分割线样式
self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
//分割线颜色
self.tableView.separatorColor = [UIColor blueColor];
//行高
self.tableView.rowHeight = 80;
//表示图的一些常用代理方法和数据源方法
#pragma mark ---------- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"A~~~ Don't Touch Me!");
}
//返回每一行cell的高度,要比设置rowHeight更灵活
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.section == 0) {
return 66;
} else if (indexPath.section == 1) {
return 88;
}
return 44;
}
//头部分区高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 50;
}
//尾部分区高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
return 30;
}
//自定义分区头部
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 44)];
headView.backgroundColor = [UIColor greenColor];
return headView;
}
//自定义分区尾部
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 44)];
footView.backgroundColor = [UIColor yellowColor];
return footView;
}
#pragma mark ---------- UITableViewDataSource
#pragma mark ---------- 必须实现的代理方法
//返回分区有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
//INSERT CODE
cell.textLabel.text = @"芒果iOS开发";
return cell;
}
#pragma mark ---------- 选择实现的代理方法
//显示有几个分区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 3;
}
//分区头部标题
- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
if (section == 0) {
return @"庄生晓梦迷蝴蝶";
} else if (section == 1) {
return @"演员盼着能得奖";
}
return @"药药切克闹";
}
//分区尾部标题
- (nullable NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
if (section == 0) {
return @"望帝春心托杜鹃";
} else if (section == 1) {
return @"写代码的盼着死同行";
}
return @"煎饼果子来一套";
}
//右侧索引内容
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
NSArray *array = @[@"k",@"z",@"s"];
return array;
}