美文网首页
ios实现原生tableView索引

ios实现原生tableView索引

作者: 小熊兜里有糖 | 来源:发表于2019-05-10 13:08 被阅读0次

先上效果图

效果图

该效果可以全程使用ios提供的原生接口实现,先看一下tableView的一些简单使用

使用uitableView需要实现两个协议

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>

实现这两个协议需要把自己作为代理对象进行传递

    myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 20, 414, 660)];
    myTableView.dataSource=self;
    myTableView.delegate=self;

协议所必须实现的二个方法

//每个section的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 20;
}

//cell的设置
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //cell重用的identify
    static NSString* flag = @"identify";
    //从重用池中获取需要的cell
    UITableViewCell* cell =[myTableView dequeueReusableCellWithIdentifier:flag];
    //获取不到则新建cell并标记identify方便以后重用
    if(cell == nil){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:flag];
        NSLog(@"新建了cell");
    }
    cell.textLabel.text = dataArray[indexPath.row];
    return cell;
}

实现索引需要的两个方法

//用于设置右侧索引表的内容数组,要求是字符串
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return indexArray;
}

//点击事件
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    //获取索引出的目标位置
    NSIndexPath* path = [NSIndexPath indexPathForRow:index inSection:0];
    
    //滚动到目标cell,使其存在于屏幕底部,需要动画
    [myTableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
    //下两行可以用来改变定位的cell的样式
    //UITableViewCell* cell = [myTableView cellForRowAtIndexPath:path];
    //cell.accessoryType=UITableViewCellAccessoryCheckmark;
    
    return index;
    
}

大功告成!!

相关文章

网友评论

      本文标题:ios实现原生tableView索引

      本文链接:https://www.haomeiwen.com/subject/lheooqtx.html