前面写了一个最简单的tableview,现在教大家在项目中运用的最多的tableview,废话不多说,上图
首先,写一个tableview的属性 :
@property (nonatomic,strong)UITableView *tableView;
初始化
- (UITableView *)tableView{
if (!_tableView) {
_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, 375, 500) style:UITableViewStylePlain];
_tableView.dataSource = self;
_tableView.delegate = self;
//这里如果不需要cell的虚线可以加上这句话:
_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
return _tableView;
}
其次,最重要的cell的初始化:
这里说明一下cell的风格:一共四种,大家可以自己写来看一下有什么不同
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
}
cell.textLabel.text = @"这是一个cell";
return cell;
}
当然,现在设置cell的高度以及数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 5;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 35;
}
如果你只是需要一个简单的cell,那么到这里,就可以了,
但实际项目中网网这些是不够的,下面我们设置tableview每一section之间的headview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 3;
//这里设置一共有几个section,这里说明一下,我们上面设置的cell的数量是在section下面的数量,这里设置了section有3个,那么说明每一个section下面的cell都有5个(上面设置的cell数量)
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 10; //这里设置的是你的head view的高度
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIView *view = [UIView new];
view.backgroundColor = [UIColor blackColor];
return view; //这个view设置的就是headview,这里可以在这个view上面添加文字,图片等等
}
//好了,到此为止,一个tableview就设置好了