在适当的部分下动态添加行而不会干扰其排序

时间:2013-12-04 17:58:07

标签: ios iphone objective-c cocoa-touch uitableview

我计划在适当的分隔符(月份作为部分)下添加假期(行)。到目前为止,我可以从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;
}

当前结果:

result

1 个答案:

答案 0 :(得分:1)

在cellForRowAtIndexPath方法中,您假设[self.sections allKeys]与您的硬编码“months”数组具有相同的顺序。解决此问题的一种方法是将“months”数组作为属性保留,然后将该行更改为:

NSDictionary *results = [[self.sections valueForKey:[[self.months objectAtIndex:indexPath.section] substringToIndex:3]] objectAtIndex:indexPath.row];

可能更好的方法是将所有内容存储在数组中而不是字典中。我可能会使用12个字典的数组,每个字典都有“月”和“假日”字段。像这样:

self.sections = @[ @{@"month":@"January",@"holidays":@[…]}, @{@"month":@"February",@"holidays":@[…]},...]