今天讨论的主题是自定义UITableView,主要包括自定义分区(包括分区表头和相关属性),字母索引(index list的相关属性)。
要实现相关功能需要实现tableview delegate。
实现自定义title section的函数是:- (UIView *)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section;
实现自定义字母索引的函数是:-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
如下贴下示例代码(各位可参考相关函数,在自己的工程中实现自定义分区和字母索引)。
#pragmamark --
#pragmamark tableView delegate
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
int i =[m_characterIndexcount];
i++;
returni;
}
-(CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section{
//返回分区头的高度
//数据类型必须为CGFloat
}
-(CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section{
//返回分区尾的高度
//数据类型必须为CGFloat
}
-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{
//定义每个分区的行数
}
-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
//每行的高度
//数据类型必须为CGFloat
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
///自定义index list/ 、、字母索引
for(UIView *indexViewin[tableView subviews])
{
if([[[indexViewclass]description]isEqualToString:@"UITableViewIndex"])
{
[indexView setFont:[UIFontsystemFontOfSize:14]];
[indexView setBackgroundColor:[UIColorclearColor]];
}
}
/
自定义UITableViewCell
}
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
return m_characterIndex;
}
-(NSInteger)tableView:(UITableView*)tableView sectionForSectionIndexTitle:(NSString*)title atIndex:(NSInteger)index{
NSIntegercount = 1;
for (NSString *characterinm_characterIndex) {
if ([character isEqualToString:title] ) {
returncount;
}
count++;
}
return 0;
}
-(NSString *)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section{
//分区头的名字
}
#pragmamark --
#pragmamark 自定义 titleof section
- (UIView *)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section{
NSString*sectionTitle=[selftableView:tableViewtitleForHeaderInSection:section];
if(sectionTitle==nil) {
returnnil;
}
// Create labelwith section title
UILabel*label=[[[UILabelalloc]init]autorelease];
label.frame=CGRectMake(13,0, 300, 31);
label.backgroundColor=[UIColorclearColor];
label.textColor=[UIColorwhiteColor];
label.text=sectionTitle;
// Createheader view and add label as a subview
UIView*sectionView=[[[UIViewalloc] initWithFrame:CGRectMake(0,0, tableView.bounds.size.width,22)] autorelease];
[sectionView setBackgroundColor:[UIColorcolorWithRed:55/255.0fgreen:159/255.0fblue:229/255.0falpha:1.0f]];
[sectionView addSubview:label];
returnsectionView;
}