项目里要求做一个带有间距的cell
效果如图:
具体实现过程:
1. 在自定义的cell里面重写cell的setFrame方法
// 重写 自定义tableviewcell的setFrame方法
- (void)setFrame:(CGRect)frame{
frame.origin.y += 4;// 整体向下移动 4
frame.size.height -= 4;
[super setFrame:frame];
}
注意:此时cell的高度要通过UITableView的代理方法进行设置
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 62.0f;
}
下面这种方式是改变不了cell的高度的
// 每行的cell要显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 1. 设置标识符
static NSString *identifier = @"cellID";
// 2. 复用cell
TVUCallListTableViewCell *tvuCell = [tableView dequeueReusableCellWithIdentifier:identifier];
// 3. 如果为空 重新创建cell
if (tvuCell == nil) {
tvuCell = [[TVUCallListTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
}
[tvuCell setFrame:CGRectMake(0, 0, kScreenWidth, 62)];
return tvuCell;
}
2. header的相关设置
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
NSString *str;
if (section == 0) {
str = @"设备";
}else{
str = @"其他";
}
return str;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 38.0f;
}
3. 这样设置只有会遇到一个问题:
当我在tabelView中为每一个section设置一个header和footer之后,滑动tableView的时候,发现header和footer并不随着tableView中的cell一起滚动,而且会在顶部或者底部停留一段时间
解决:
方法一只能解决header的粘性问题:
方法一:
//去掉UItableview headerview黏性 (保持在tableView的顶部)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
if (scrollView == self.tvuCallListTableView) {
// 每一个组组头的高度
CGFloat sectionHeaderHeight = 38.0f;
if (scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y >= 0) {
scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
}else if (scrollView.contentOffset.y >= sectionHeaderHeight) {
scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
}
}
}
方法二:
同时解决header和footer的粘性
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (scrollView == self.self.tvuCallListTableView)
{
UITableView *tableview = (UITableView *)scrollView;
CGFloat sectionHeaderHeight = 38;
CGFloat sectionFooterHeight = 76;
CGFloat offsetY = tableview.contentOffset.y;
if (offsetY >= 0 && offsetY <= sectionHeaderHeight)
{
tableview.contentInset = UIEdgeInsetsMake(-offsetY, 0, -sectionFooterHeight, 0);
}else if (offsetY >= sectionHeaderHeight && offsetY <= tableview.contentSize.height - tableview.frame.size.height - sectionFooterHeight){
tableview.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, -sectionFooterHeight, 0);
}else if (offsetY >= tableview.contentSize.height - tableview.frame.size.height - sectionFooterHeight && offsetY <= tableview.contentSize.height - tableview.frame.size.height){
tableview.contentInset = UIEdgeInsetsMake(-offsetY, 0, -(tableview.contentSize.height - tableview.frame.size.height - sectionFooterHeight), 0);
}
}
}
【注】如果对
scrollView的
contentInse
contentOffset 等属性不理解 可以参考 这篇文章