TableView索引准确定位

在做项目的过程中,我遇到这样一个问题,就是本身的tableview 调用

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView

方法的时候,最后几个位置点击后不能准确定位,比如说“#” 不管我如何点击“#”都无法把其对应的列表项显示出来,所以我自己在

- (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index

方法中重写了一些方法 代码如下

- (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
  //1.获取当前index的section的original的y
  //2.用tableview.contentsize.height减去y,得到lefty
  //3.如果lefty>=tableview.frame.size.height 滚动lefty个单位
  //4.如果lefty<tableview.frame.size.height 滚动tableview.contentsize.height-tableview.frame.size.height
  float y = [self getYOffSet:index title:title];
  if (tableView.contentSize.height-y>=tableView.frame.size.height) {
     [tableView setContentOffset:CGPointMake(0, y) animated:NO];
  }else{
     [tableView setContentOffset:CGPointMake(0, tableView.contentSize.height-tableView.frame.size.height) animated:NO];
  }
  return NSNotFound;
}

//22是断头高度,50是每行高度,100是上面无索引部分附加的高度

-(float)getYOffSet:(NSInteger)index title:(NSString *)title{
//这里的offy = 100 是我在这个tableview最上面加了两个section 不在这个计算之内 显示了别的东西 对于不需要添加特别提示等//显示,可以设置为0
float offY = 100;
    int count = 0;
//对应的所有内容的高度
    float addOffy = 0;
//对应标题下内容不为空 例:以a开头的内容有aaa,abc,abcd 则a标题下不为空,addTitleCount加1 计数用 通过这个计算一共有
//多少项内不为空 总共占用多少header高度 最后一句中得22是我定义的一个viewforHeader的高度
float addTitleCount = 0;
//sectionTitles 是从a-z加上#之后的列表
//datasource 是对应我的没个section中有几项内容的数据
  for (NSString * string in self.sectionTitles) {
    if ([string isEqualToString:title]) {
      break;
    }
    addOffy+=50*[[self.dataSource objectAtIndex:count] count];
    if ([[self.dataSource objectAtIndex:count] count]!=0) {
      addTitleCount++;
    }
    count++;
     
  }
  
  return offY+22*(addTitleCount)+addOffy;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容