我计划在适当的分隔符(月份为节)下添加假日(行)。到目前为止,我可以从plist检索数据,并创建具有预定义主题的部分(持续12个月),但是我无法找出在适当月份内添加假期的正确方法。
@synthesize event, sections;
- (void)viewDidLoad {
self.event = [NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"2013" ofType:@"plist"]];
self.sections = [[NSMutableDictionary alloc] init];
BOOL found;
for (NSDictionary *oneEvent in self.event)
{
NSString *c = [[oneEvent objectForKey:@"date"] substringToIndex:3];
found = NO;
for (NSString *str in [self.sections allKeys])
{
if ([str isEqualToString:c])
{
found = YES;
}
}
if (!found)
{
[self.sections setValue:[[NSMutableArray alloc] init] forKey:c];
}
}
for (NSDictionary *oneEvent in self.event)
{
[[self.sections objectForKey:[[oneEvent objectForKey:@"date"] substringToIndex:3]] addObject:oneEvent];
}
[super viewDidLoad];
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[self.sections allKeys] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSArray *months = [[NSArray alloc]initWithObjects:@"January",@"February",@"March",@"April",@"May",@"June",@"July",@"August",@"September",@"October",@"November",@"December", nil];
return [months objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[self.sections valueForKey:[[self.sections allKeys] objectAtIndex:section]] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
NSDictionary *results = [[self.sections valueForKey:[[self.sections allKeys] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.text = [results objectForKey:@"date"];
cell.detailTextLabel.text = [results objectForKey:@"event"];
return cell;
}
当前结果:
最佳答案
在cellForRowAtIndexPath方法中,假定[self.sections allKeys]与硬编码的“ months”数组具有相同的顺序。解决此问题的一种方法是将“ months”数组保留为一个属性,然后将该行更改为此:
NSDictionary *results = [[self.sections valueForKey:[[self.months objectAtIndex:indexPath.section] substringToIndex:3]] objectAtIndex:indexPath.row];
可能更好的方法是将所有内容存储在数组中,而不是字典中。我可能会使用12个词典的数组,每个词典都有“ month”和“ holidays”字段。像这样:
self.sections = @[ @{@"month":@"January",@"holidays":@[…]}, @{@"month":@"February",@"holidays":@[…]},...]
关于ios - 在适当的部分下动态添加行,而不会影响其排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20382518/