uitableview - данные и if (! cell) - PullRequest
       13

uitableview - данные и if (! cell)

0 голосов
/ 20 февраля 2012

У меня большая проблема с UITableView, я хочу использовать метку внутри ячейки, поэтому я использую этот метод для этого

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"ItemCell";

// If the indexPath is less than the numberOfItemsToDisplay, configure and return a normal cell,
// otherwise, replace it with a button cell.

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
else {

}

if (indexPath.section == 0) {

    elemento = [array objectAtIndex:indexPath.row];

    UILabel *labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 220, 30)];
    labelTitle.text = [elemento objectForKey:@"Titolo"];
    labelTitle.backgroundColor = [UIColor clearColor];
    labelTitle.textColor = [UIColor whiteColor];
    [cell addSubview:labelTitle];

} else {

    UILabel *labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 220, 30)];
    labelTitle.text = @"Read More";
    labelTitle.backgroundColor = [UIColor clearColor];
    labelTitle.textColor = [UIColor whiteColor];
    [cell addSubview:labelTitle];

}


return cell;

}

таким образом я могу видеть все данные в моей таблице, но метка перекрывается, чем я пытаюсь использовать этот метод

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"ItemCell";

// If the indexPath is less than the numberOfItemsToDisplay, configure and return a normal cell,
// otherwise, replace it with a button cell.

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

    if (indexPath.section == 0) {

        elemento = [array objectAtIndex:indexPath.row];

        UILabel *labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 220, 30)];
        labelTitle.text = [elemento objectForKey:@"Titolo"];
        labelTitle.backgroundColor = [UIColor clearColor];
        labelTitle.textColor = [UIColor whiteColor];
        [cell addSubview:labelTitle];

    } else {

        UILabel *labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 220, 30)];
        labelTitle.text = @"Read More";
        labelTitle.backgroundColor = [UIColor clearColor];
        labelTitle.textColor = [UIColor whiteColor];
        [cell addSubview:labelTitle];

    }

}
else {

}

return cell;

}

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

Например, если в первом случае на моей таблице я вижу: 1,2,3,4,5,6,7,8,9,10, ... во втором случае я вижу: 1,2,3,4,5,1,2,3,4,5,1,2,3,4,5, ...

в чем проблема?

Ответы [ 2 ]

1 голос
/ 20 февраля 2012

добавить этот код

  for (UIView *view in [cell.contentView subviews]) 
    {
        [view removeFromSuperview];
    }

до

if (indexPath.section == 0) {

elemento = [array objectAtIndex:indexPath.row];

UILabel *labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 220, 30)];
labelTitle.text = [elemento objectForKey:@"Titolo"];
labelTitle.backgroundColor = [UIColor clearColor];
labelTitle.textColor = [UIColor whiteColor];
[cell addSubview:labelTitle];

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

0 голосов
/ 20 февраля 2012

Код, который вы опубликовали, задает UITableViewCellStyleSubtitle в качестве стиля ячейки, что означает, что каждая ячейка будет иметь текстовую метку и текстовую метку с подробным описанием в соответствующих свойствах textLabel и detailTextLabel. Таким образом, у вас нет причин выделять дополнительные экземпляры UILabel. Вместо этого просто заполните text свойства существующих меток. Например, вы можете переписать вашу реализацию так:

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellID = @"ItemCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellID];
        cell.textLabel.backgroundColor = [UIColor clearColor];
        cell.textLabel.textColor = [UIColor whiteColor];

    }

    cell.textLabel.text = (indexPath.section == 0 ?
                           [array objectAtIndex:indexPath.row] :
                           @"ReadMore");    

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