UITableViewCell с UITableViewCellStyleValue1, добавление новой строки в detailTextLabel в ячейке внизу - PullRequest
4 голосов
/ 29 мая 2010

в моем табличном виде у меня есть последняя ячейка, которая изначально не видна, как видно на первом изображении, когда я прокручиваю список вверх, на втором изображении вы можете видеть, что цена или мой detailTextLabel помещены в новую строку поддерживая правильное обоснование.
изображение 1 http://img706.imageshack.us/img706/4496/iphoneerror1.jpg

изображение 2 http://img706.imageshack.us/img706/6007/iphoneerror2edited.jpg


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

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [ltableView dequeueReusableCellWithIdentifier:CellIdentifier];    
    // Configure the cell.
    NSUInteger indexRow = [indexPath row];
    switch (indexRow) {
        case 0:{
            NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet];
            NSString *description = [[currentData objectForKey:@"Description"] stringByTrimmingCharactersInSet:set];

            if (cell == nil) {
                    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
            }
            cell.selectionStyle =  UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryNone;
            cellShift = 1;


            if (![description isEqualToString:@""]) {
                cell.textLabel.text = @"";
                cell.detailTextLabel.text = description;
                cell.detailTextLabel.numberOfLines = 2;
            }
            else {
                cell.textLabel.text = @"";
                cell.detailTextLabel.text = @"";
                cell.detailTextLabel.numberOfLines = 0;


            }
            break;
        }
        default:{
            if (cell == nil) {
                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
            }
            NSDictionary *item = [tableData objectAtIndex:(indexRow-cellShift)];
            NSString *name = [item objectForKey:@"Name"];
            if ([name length] > MaxVendorsLength ) {
                name =  [NSString stringWithFormat:@"%@ ...",[name substringToIndex:MaxVendorsLength]];
            }
            cell.textLabel.text = name;
            cell.textLabel.minimumFontSize = 12;

            NSString *priceString;
            float price = [[item objectForKey:@"Price"] floatValue];
            //NSLog(@"| %@ | : | %@ |",[item objectForKey:@"Name"], [item objectForKey:@"Price"]);
            if (price != 0) {
                priceString = [[NSString alloc] initWithFormat:@"$%.2f",price];
            }
            else {
                priceString = [[NSString alloc] initWithString:@"--"];
            }

            cell.detailTextLabel.text =  priceString;

            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            [priceString release];          
            break;
        }
    }
    cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
    cell.textLabel.minimumFontSize = 14;
    cell.detailTextLabel.font = [UIFont boldSystemFontOfSize:15];
    cell.detailTextLabel.minimumFontSize = 14;
    return cell;
}

Дайте мне знать, если мне нужно опубликовать что-нибудь еще, чтобы получить помощь с этим ???

Ответы [ 3 ]

9 голосов
/ 29 мая 2010

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

static NSString *FirstRowCellIdentifier = @"A";
static NSString *OtherRowCellIdentifier = @"B";

NSString *cellIdentifier = nil;
if ([indexPath row] == 0)
    cellIdentifier = FirstRowCellIdentifier;
else
    cellIdentifer = OtherRowCellIdentifier;

UITableViewCell *cell = [ltableView dequeueReusableCellWithIdentifier:cellIdentifier];
// .....

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

2 голосов
/ 29 мая 2010

Вы используете один и тот же идентификатор ячейки для всех строк, но 0-я строка имеет другой стиль. При прокрутке вверх ячейка в стиле субтитров может повторно использоваться.

Попробуйте использовать другой идентификатор ячейки для 0-й строки. Оставьте только объявление cell вне коммутатора и переместите dequeueReusableCellWithIdentifier для каждого случая.

1 голос
/ 11 февраля 2014
 (UITableViewCell *)tableView:(UITableView *)ltableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...