Нежелательный пустой UITableViewCell в верхней части моего UITableView - PullRequest
5 голосов
/ 11 августа 2011

У меня есть UITableView с 1 ​​пустой строкой вверху, и я не могу понять, почему. Вот соответствующий код, вы, ребята, знаете, что здесь происходит?

UITableView загружается без содержимого. Этот метод запускает каждое обновление данных после:

- (IBAction)updateButton:(id)sender 
{
    if (questionsTextField.isFirstResponder) {
        [questionsTextField resignFirstResponder];
        [self assignQuestionsCount];
    }

    if (currentNumberOfQuestions > 0) {
        // do work calculating
        currentTest = nil;

        currentTest = [self retrieveCurrentTest];
        currentTest.numberOfQuestions = currentNumberOfQuestions;
        currentTest.decimalPlacesToDisplay = 0;
        currentTest.roundingBreakPoint = 0.5;

        currentGradeScale = nil;
        currentGradeScale = [currentTest generateGradingScale];
        [scoresTableView reloadData];
    }
    else {
        // my error handling on text boxes here....
    }
}

Вот моя реализация методов UITableView:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.currentGradeScale count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"scoresIndentifier";
    static int missedTag = 1, correctTag = 2, gradeTag = 3;

    UILabel *missedLabel, *correctAndTotalLabel, *letterGradeLabel;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    //if a cell does not exist, get it then initialize it
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

        // populate data
        missedLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 100, 50)];
        missedLabel.tag = missedTag;
        missedLabel.font = [UIFont systemFontOfSize:14.0];
        missedLabel.textAlignment = UITextAlignmentCenter;
        missedLabel.textColor = [UIColor blackColor];
        missedLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight |UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth;
        [cell.contentView addSubview:missedLabel];

    }
    // if it does, just reassign the properties
    else {
        missedLabel = (UILabel *)[cell.contentView viewWithTag:missedTag];
    }

    missedLabel.text = [[self.currentGradeScale objectAtIndex:indexPath.row] determineLetterGrade:0.5];

    return cell;
}

Спасибо за помощь, я очень ценю это.

Ответы [ 2 ]

1 голос
/ 12 сентября 2012

У меня была такая же проблема, и я обнаружил, что в области Размер прокрутки / Вставки содержимого / Верхняя часть есть значение.Смотрите прикрепленное изображение.Как только я установил 0 и сохранил, пустая область вверху исчезла.Надеюсь, это поможет.

enter image description here

1 голос
/ 11 августа 2011

Наиболее очевидное объяснение, которое вы, вероятно, уже рассмотрели, заключается в том, что в первой строке таблицы заданы пустые данные (т. Е. Self.currentGradeScale objectAtIndex: 0 возвращает nil или @ "" для "определенного уровня букв 0,5".) )

Если вы поставили точку останова на cellForRowAtIndexPath в отладчике в строке, где вы присваиваете значение тексту метки, это определенно задает непустое / непустое значение для строки 0?

Кроме того, обратите внимание, что в missedLabel есть утечка памяти - добавление ее в качестве подпредставления в ячейку сохранит ее, поэтому вы должны автоматически высвобождать ее при выделении или освобождать после добавления в качестве подпредставления.

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