添加索引

来源:互联网 发布:淘宝的收费方式 编辑:程序博客网 时间:2024/06/05 04:30

最近公司需要做城市相关内容,就好好研究了下如何添加索引

效果如图:





实现过程如下:

一、添加

UITableView添加的两个代理方法UITableViewDataSource, UITableViewDelegate

二、初始化UITableView,然后注意属性:

self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 100+64) style:UITableViewStylePlain];
    myTableView.dataSource = self;
    myTableView.delegate = self;
    myTableView.allowsSelection=YES;
    myTableView.showsHorizontalScrollIndicator = NO;
    myTableView.showsVerticalScrollIndicator = NO;
    //设置索引列文本的颜色
    myTableView.sectionIndexColor = [UIColorredColor];
    [self.view addSubview:myTableView];

三、第三步:添加索引的数据 indexArr,里面可以直接时“A”、“B”…………等大写字母字符串;

四、相关代理的使用

//添加索引列
  
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  
{
    
    return indexArr;
  
}

//索引列点击事件
  
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  
{
  
 NSLog(@"===%@  ===%d",title,index);
  
 //点击索引,列表跳转到对应索引的行
  
 [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index]
 atScrollPosition:UITableViewScrollPositionTop animated:YES];
  
 return index;
  
}

五、在- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section中添加元素

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UIView *headView = [[[UIView alloc]init]autorelease];
    headView.backgroundColor = [UIColor clearColor];
    
    //标题背景
    UIView *biaotiView = [[[UIView alloc]init]autorelease];
    biaotiView.backgroundColor = BB_White_Color;
    biaotiView.frame=CGRectMake(0, 0, 320, 30);
   [headView addSubview:biaotiView];
         
    //标题文字
    UILabel *lblBiaoti = [[[UILabel alloc]init]autorelease];
    lblBiaoti.backgroundColor = [UIColor clearColor];
    lblBiaoti.textAlignment = NSTextAlignmentLeft;
    lblBiaoti.font = [UIFont systemFontOfSize:15];
    lblBiaoti.textColor = [UIColor blackColor];
    lblBiaoti.frame = CGRectMake(15, 7.5, 200, 15);
    lblBiaoti.text = [headerList objectAtIndex:section-1];
    [biaotiView addSubview:lblBiaoti];
    
    return headView;
}



0 0
原创粉丝点击