添加索引

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

效果如图:





实现过程如下:

一、添加

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 = [UIColor redColor];
     [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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值