如何按日期划分 UITableView 的各个部分

How to divide sections of UITableView by Date

我有一个分为单元格的 TableView。单元格的文本是 fireDate 到 UILocalNotification。这是我的代码:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [[[UIApplication sharedApplication]scheduledLocalNotifications]count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{    
    cellView *cell = (cellView *)[tableView dequeueReusableCellWithIdentifier: @"Cell" forIndexPath:indexPath];
    NSArray *localnotifications = [[UIApplication sharedApplication]scheduledLocalNotifications];
    UILocalNotification *localNotification = [localnotifications objectAtIndex:indexPath.row];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM/dd/yyyy"];
    NSString *timeString = [formatter stringFromDate:localNotification.fireDate];
    [cell.textlabel setText:timeString];
    return cell;
}

如何创建按日期划分的部分?

First your section numbers must be the count of the array

  • (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return 节数。 return [[[UIApplication sharedApplication]scheduledLocalNotifications]count]; }

The number of rows must be one per section

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 1;
}

Here give a name for each section i dont know the structure of your array but if its a dictionary for example : objectForKey:@"date"...

- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [NSString stringWithFormat:@"%@", [[[UIApplication sharedApplication]scheduledLocalNotifications] objectAtIndex:section];
}

In cellForRowAtIndexPath first check the indexPath.section and set your object like you usually do with one section

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{    
    switch (indexPath.section) {
        case indexPath.row:
       // fill your cell // 
        default:
        break;
    }

}

我附近没有电脑可以测试 我凭记忆告诉你这些我希望你至少知道 tableView 是如何工作的。

祝你好运。