我正在尝试学习如何对UITableView进行编码,并且对该节的编程存在一些问题。
我用字符串声明了3个数组,并用3个数组声明了1个数组。
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之类的数组的名称实际显示节的名称?
最佳答案
就您而言,最好将数组存储在NSDictionary
中。例如,如果您声明并合成了一个名为NSDictionary
的tableContents
变量和一个名为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];
}
然后在
cellForRowAtIndexPath
方法中访问每个数组的内容:- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
NSArray *arrayForCurrentSection = [self.tableContents objectForKey:[NSString stringWithFormat:@"%d",indexPath.section]];
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:SimpleTableIdentifier] autorelease];
}
cell.textLabel.text = [arrayForCurrentSection objectAtIndex:indexPath.row];
return cell;
}
关于ios - 嵌套NSArray的UITableView中的不同节标题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10155544/