UItableView напечатаны несколько данных - PullRequest
0 голосов
/ 22 апреля 2011

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

Это мой код

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

    UITableViewCell *cell = [tableView  dequeueReusableCellWithIdentifier:@"cellID"];

    if (!cell)
    {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"cellID"] autorelease];  
    }
 /*
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    */

    if(indexPath.section == 0)
    {
        cell.backgroundColor = [UIColor clearColor];
        cell.accessoryType = UITableViewCellAccessoryNone;

        float rowHeight = [DetailViewController calculateHeightOfTextFromWidth:[dict objectForKey:@"golf_name"] :[UIFont boldSystemFontOfSize:18] :290 :UILineBreakModeTailTruncation];

        UILabel *categorName = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 290, rowHeight)];
        categorName.font = [UIFont boldSystemFontOfSize:20];
        categorName.numberOfLines = 5;
        categorName.backgroundColor = [UIColor clearColor];
        categorName.textColor = [UIColor whiteColor];
        categorName.text = [dict objectForKey:@"golf_name"];
        [cell addSubview:categorName];
        [categorName release];
    }
    if(indexPath.section == 1)
    {
        cell.backgroundColor = [UIColor whiteColor];
        cell.accessoryType = UITableViewCellAccessoryNone;

        UILabel *categorName = [[UILabel alloc] initWithFrame:CGRectMake(50, 10, 70, 20)];
        categorName.font = [UIFont boldSystemFontOfSize:15];
        categorName.numberOfLines = 5;
        categorName.backgroundColor = [UIColor clearColor];
        categorName.textColor = [UIColor colorWithRed:145.0f/255.0f green:162.0f/255.0f blue:184.0f/255.0f alpha:1];
        categorName.text = @"Phone";
        [cell addSubview:categorName];
        [categorName release];

        UILabel *phone = [[UILabel alloc] initWithFrame:CGRectMake(110, 10, 290, 20)];
        phone.font = [UIFont boldSystemFontOfSize:15];
        phone.numberOfLines = 5;
        phone.backgroundColor = [UIColor clearColor];
        //categorName.textColor = [UIColor colorWithRed:145.0f/255.0f green:162.0f/255.0f blue:184.0f/255.0f alpha:1];
        phone.text = [dict objectForKey:@"golf_phone"];
        [cell addSubview:phone];
        [phone release];
    }
    if(indexPath.section == 2)
    {
        cell.backgroundColor = [UIColor whiteColor];
        cell.accessoryType = UITableViewCellAccessoryNone;

        UILabel *categorName = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 90, 20)];
        categorName.font = [UIFont boldSystemFontOfSize:15];
        categorName.numberOfLines = 5;
        categorName.backgroundColor = [UIColor clearColor];
        categorName.textColor = [UIColor colorWithRed:145.0f/255.0f green:162.0f/255.0f blue:184.0f/255.0f alpha:1];
        categorName.text = @"Home page";
        [cell addSubview:categorName];
        [categorName release];

        UILabel *phone = [[UILabel alloc] initWithFrame:CGRectMake(110, 10, 230, 20)];
        phone.font = [UIFont boldSystemFontOfSize:15];
        phone.numberOfLines = 5;
        phone.backgroundColor = [UIColor clearColor];
        //categorName.textColor = [UIColor colorWithRed:145.0f/255.0f green:162.0f/255.0f blue:184.0f/255.0f alpha:1];
        phone.text = [dict objectForKey:@"golf_url"];
        [cell addSubview:phone];
        [phone release];
    }  
.......  
.....  
return cell;  
}

Ответы [ 3 ]

1 голос
/ 22 апреля 2011

Обновление

Мой оригинальный ответ не был правильным способом повторного использования UITableViewCell. Никогда не следует использовать «CellID% d% d» (indexPath.row & indexPath.column) в качестве идентификатора ячейки, что противоречит самой цели повторного использования ячейки. Он создаст отдельный UITableViewCell для каждой строки в таблице, и каждая из этих ячеек останется в памяти. Представьте, что произойдет, если у вас есть tableView с около 1000 строк.

Реальный ответ на вопрос OP: не забудьте сбросить UITableViewCell, возвращаемый dequeueReusableCellWithIdentifier, поскольку он может вернуть ячейку, которая уже используется, и заполненный пользовательский интерфейс. Например, если вы не сбросили тексты в UILabel, он может содержать строки, которые должны были быть показаны в другой строке вашего tableView.

Мой оригинальный ответ (не используйте это)

Хирен, просто попробуй,

UITableViewCell *cell = [tableView  dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"CellID%d%d",indexPath.section,indexPath.row]];
if (!cell){
 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:[NSString stringWithFormat:@"CellID%d%d",indexPath.section,indexPath.row]] autorelease];  
}

вместо

UITableViewCell *cell = [tableView  dequeueReusableCellWithIdentifier:@"cellID"];
if (!cell)
{
   cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"cellID"] autorelease];  
}

Пожалуйста, прочитайте это .. вы поймете, как дать идентификаторы ячеек ..

0 голосов
/ 22 апреля 2011

попробуйте добавить любой цвет, потому что clearcolor делает этикетку прозрачной.

0 голосов
/ 22 апреля 2011

Когда вы создаете объект UITableView, установите rowHeight для каждой ячейки.

myTableView.rowHeight = 50; //Depend on your requirement,

Дайте мне знать, если вам все еще трудно добиться желаемого результата.

Если высота вашей ячейки не постоянна, тогда реализуйте метод heightForRowAtIndexPath,

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

И вернуть разную высоту-2 для каждой ячейки.

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