我正在尝试学习如何编写UITableView,并且对该部分的编程存在一些问题。
我已经声明了3个带字符串的数组和1个带有3个数组的数组。
firstSection = [NSArray arrayWithObjects:@"Red", @"Blue", nil];
secondSection = [NSArray arrayWithObjects:@"Orange", @"Green", @"Purple", nil];
thirdSection = [NSArray arrayWithObject:@"Yellow"];
array = [[NSMutableArray alloc] initWithObjects:firstSection, secondSection, thirdSection, nil];
显示标题
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
NSString * title;
title = [NSString stringWithFormat:@"%@" , [array objectAtIndex:section]];
return title;
}
将数组本身显示为标题
因此是否可以使用诸如firstSection和secondSection等数组的名称来实际显示部分的名称?
答案 0 :(得分:6)
在您的情况下,最好将数组存储在NSDictionary
中。例如,如果您声明并合成名为NSDictionary
的{{1}}变量和名为tableContents
的{{1}}变量,则可以执行以下操作:
NSArray
然后在表视图中使用控制器方法:
titleOfSections
然后使用 - (void)viewDidLoad {
[super viewDidLoad];
//These will automatically be released. You won't be needing them anymore (You'll be accessing your data through the NSDictionary variable)
NSArray *firstSection = [NSArray arrayWithObjects:@"Red", @"Blue", nil];
NSArray *secondSection = [NSArray arrayWithObjects:@"Orange", @"Green", @"Purple", nil];
NSArray *thirdSection = [NSArray arrayWithObject:@"Yellow"];
//These are the names that will appear in the section header
self.titleOfSections = [NSArray arrayWithObjects:@"Name of your first section",@"Name of your second section",@"Name of your third section", nil];
NSDictionary *temporaryDictionary = [[NSDictionary alloc]initWithObjectsAndKeys:firstSection,@"0",secondSection,@"1",thirdSection,@"2",nil];
self.tableContents = temporaryDictionary;
[temporaryDictionary release];
}
方法访问每个数组的内容:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return [self.titleOfSections count];
}
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
return [[self.tableContents objectForKey:[NSString stringWithFormat:@"%d",section]] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//Setting the name of your section
return [self.titleOfSections objectAtIndex:section];
}
答案 1 :(得分:0)
NSArray *SectionArray = [[NSArray alloc]initwithArray:[array objectAtIndex:section]];
NSString * title;
title = [NSString stringWithFormat:@"%@" , [SectionArray objectAtIndex:section]];
return title;