我正在尝试学习如何编写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];
Run Code Online (Sandbox Code Playgroud)
显示标题
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
NSString * title;
title = [NSString stringWithFormat:@"%@" , [array objectAtIndex:section]];
return title;
}
Run Code Online (Sandbox Code Playgroud)
它将数组本身显示为标题
因此,是否可以使用诸如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];
}
Run Code Online (Sandbox Code Playgroud)
然后在表视图中使用控制器方法:
- (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];
}
Run Code Online (Sandbox Code Playgroud)
然后访问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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2689 次 |
最近记录: |