Как добавить только один раздел и заголовки разделов в UITableView? - PullRequest
0 голосов
/ 29 октября 2011

Мне нужно добавить еще один раздел в мое табличное представление, которое произойдет один раз в верхней части таблицы.Я также хочу использовать пользовательский вид, чтобы можно было хорошо форматировать содержимое.

На рисунке ниже вы можете видеть, что у меня есть заголовки разделов и строки под каждым.

Я пробовал несколько раз, но я немного сбит с толку относительно того, сколько секций у меня должно быть и логики, чтобы показать все строки, которые мне нужны.Чтобы еще больше усложнить ситуацию, я также отображаю одну строку с одним разделом, с текстом, в котором говорится, что строки недоступны.В этом случае я хочу показать мой новый раздел и этот текст.

enter image description here

Вот мой код ..

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    int count = [sectionTitles count];
    if (count == 0) {
        return 1;
    } else {
        return count;
    }
}  

//

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
          (NSInteger)section {
    int count = 0;
    if (sectionRowCounts.count != 0) {
        NSString *title = [sectionTitles objectAtIndex:section];
        count = [[sectionRowCounts objectForKey:title] intValue];
    }
    return (count ? count : 1);
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:
     (NSInteger)section {
    NSString *title = @"";
    if (sectionTitles.count != 0 ) {
        title = [sectionTitles objectAtIndex:section];
    }
    return title;
}

//

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:
   (NSInteger)section {
     if (sectionTitles.count == 0 ) {
         UIView *customView = [[[UIView alloc] init] autorelease];
        return customView;
    } 

    HeaderSectionReportView *customView = [[[HeaderSectionReportView alloc] 
       initWithFrame:CGRectMake(0.0, 0.0, 360.0, 20.0)] autorelease];

    // create the button object
    UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    headerLabel.frame = CGRectMake(10.0, 0.0, 100.0, 20.0); 
    headerLabel.text = [sectionTitles objectAtIndex:section];
    [customView addSubview:headerLabel];
    [headerLabel release];

    return customView;
}

- (CGFloat) tableView:(UITableView *)tableView 
         heightForHeaderInSection:(NSInteger)section {
    return 20.0;
}

//

- (UITableViewCell *)tableView:(UITableView *)tableView 
           cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell1;
    if(rowSections.count == 0) {

        cell1 = [[[UITableViewCell alloc] initWithStyle:
             UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];

        UIView *view = [[[UIView alloc] init] autorelease];
        view.backgroundColor = [UIColor clearColor];
        cell1.selectedBackgroundView = view;

        cell1.textLabel.text = @"No transactons found";
        return cell1;
    }

    NSString *strRowSection = [NSString stringWithFormat:@"%i-%i", 
         indexPath.section, indexPath.row];
    NSInteger intDBRow = [rowSections indexOfObject:strRowSection];
    static NSString *CellIdentifier = @"ReportCell";

    ReportCell *cell = (ReportCell *) [tableView 
          dequeueReusableCellWithIdentifier:CellIdentifier];

//

    if (cell == nil) {
        NSArray *topLevelObjects = [[NSBundle mainBundle] 
         loadNibNamed:@"ReportCell" owner:nil options:nil];

        for (id currentObject in topLevelObjects) {
            if ([currentObject isKindOfClass:[UITableViewCell class]]) {
                cell = ((ReportCell *) currentObject);
                break;
            }
        }
    }

    NSString *desc = [[transactionsArray objectAtIndex:intDBRow] 
            objectForKey:@"desc"];
    cell.descriptionValue.text = desc;

    UIView *view = [[[UIView alloc] init] autorelease];
    view.backgroundColor = [UIColor clearColor];
    cell.selectedBackgroundView = view;

    return cell;

}

//

- (void) populateDataSource {

    int sectionIncr = -1;
    int rowIncr = 0;

    sectionTitles = [[NSMutableArray alloc] initWithObjects:nil];
    sectionRowCounts = [[NSMutableDictionary alloc] init];
    rowSections = [[NSMutableArray alloc] initWithObjects:nil];

    NSMutableArray *arrayTmp= [[NSMutableArray alloc] init];

    //populate array

    self.transactionsArray = arrayTmp;
    [arrayTmp release];

}

1 Ответ

2 голосов
/ 29 октября 2011

Хотя вы, конечно, могли бы просто добавить еще один раздел в начале с пользовательским представлением, связанным с ним, есть еще один вариант. Вы можете назначить пользовательское представление свойству UITableView 'tableHeaderView', см. tableHeaderView в документации Apple.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...