UITableView自定義分割槽和自定義字母索引(包括自定義索引的字型和顏色)
今天討論的主題是自定義UITableView,主要包括自定義分割槽(包括分割槽表頭和相關屬性),字母索引(index list的相關屬性)。
要實現相關功能需要實現tableview delegate。
實現自定義title section的函式是:- (UIView *)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section;
實現自定義字母索引的函式是:-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
如下貼下示例程式碼(各位可參考相關函式,在自己的工程中實現自定義分割槽和字母索引)。
#pragmamark --
#pragmamark tableView delegate
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
int i =[m_characterIndexcount];
i++;
returni;
}
-(CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger
//返回分割槽頭的高度
//資料型別必須為CGFloat
}
-(CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section{
//返回分割槽尾的高度
//資料型別必須為CGFloat
}
-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{
//定義每個分割槽的行數
}
-(CGFloat)tableView:(UITableView
{
//每行的高度
//資料型別必須為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;
}