UITableViewCell - перекрытие с содержимым предыдущих ячеек - PullRequest
10 голосов
/ 25 января 2011

У меня странная проблема с моим столом

  1. У меня есть около 20 ячеек для отображения
  2. Высота каждой ячейки около 84 пикселей
  3. Когда я не нажимаю на ячейку, я установил цвет фона
  4. Первые 4 ячейки в порядке, но когда я прокручиваю вниз и нажимаю на 5-ю ячейку, содержимое каждой ячейки начинает перекрываться с некоторым другим содержимым, обычно содержимым из первых 4 ячеек.

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

Вот мой код, и я тоже добавлю несколько фотографий Cell with overlapped content

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 104;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

     return [stores count];
}

-(UITableViewCell *)tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    CGRect Label1Frame = CGRectMake(5, 5, 250, 30);
    CGRect Label2Frame = CGRectMake(6, 42, 220, 20);    
    CGRect Label3Frame = CGRectMake(6, 62, 220, 20);        
    CGRect Label4Frame = CGRectMake(240,56, 70, 12);            

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if(cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    }else{
        // a cell is being recycled, remove the old edit field (if it contains one of our tagged edit fields)
        UIView *viewToCheck = nil;
        viewToCheck = [cell.contentView viewWithTag:1];
        if (!viewToCheck) {
            [viewToCheck removeFromSuperview];
            DebugLog(@"View removed");
        }       
    }
    //cell.selectionStyle=UITableViewCellSelectionStyleNone;
    [cell setSelectedBackgroundView:bgView];    
    NSInteger row=indexPath.row;
    UILabel *lblTemp;
    [[cell contentView] clearsContextBeforeDrawing];

    //Line 1

    lblTemp=[[UILabel alloc] initWithFrame: Label1Frame];
    lblTemp.tag=1;
    lblTemp.text=[[stores objectAtIndex:row] objectAtIndex:0] ;
    lblTemp.numberOfLines=2;
    lblTemp.font = [UIFont boldSystemFontOfSize:13];
    lblTemp.adjustsFontSizeToFitWidth=YES;
    lblTemp.minimumFontSize=12;
    lblTemp.textColor = [UIColor grayColor];
    [cell.contentView addSubview:lblTemp];  
    [lblTemp release];
    //Line 2
    lblTemp = [[UILabel alloc] initWithFrame:Label2Frame];
    lblTemp.tag = 2;
    lblTemp.text=[[stores objectAtIndex:row]objectAtIndex:1];   
    lblTemp.font = [UIFont systemFontOfSize:12];
    lblTemp.textColor = [UIColor grayColor ];
    lblTemp.textAlignment=UITextAlignmentLeft;
    lblTemp.adjustsFontSizeToFitWidth=YES;
    lblTemp.minimumFontSize=12;

    [cell.contentView addSubview:lblTemp];  
    [lblTemp release];

    //Line 3    
    lblTemp = [[UILabel alloc] initWithFrame:Label3Frame];
    lblTemp.tag = 3;
    lblTemp.text=[[stores objectAtIndex:row]objectAtIndex:2];
    lblTemp.font = [UIFont systemFontOfSize:12];
    lblTemp.textColor = [UIColor grayColor ];
    [cell.contentView addSubview:lblTemp];      
    [lblTemp release];
    //Phone button
    UIButton *phoneButton=[[UIButton alloc] initWithFrame:CGRectMake(240,16,30,30)];
    [phoneButton setBackgroundImage:[UIImage imageNamed:@"phone.png"] forState:UIControlStateNormal];
    [phoneButton setTag:row];
    [phoneButton addTarget:self action:@selector(dialNumber:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:phoneButton];
    //ANnotation button
    UIButton *annotation=[[UIButton alloc] initWithFrame:CGRectMake(274,16,30,30)]; 
    [annotation setTag:row];
    [annotation setBackgroundImage:[UIImage imageNamed:@"tab.png"] forState:UIControlStateNormal];
    [annotation addTarget:self action:@selector(openMap:) forControlEvents:UIControlEventTouchUpInside];    
    [cell.contentView addSubview:annotation];   
    [annotation release];
    //Distance label
    //Line 3    
    lblTemp = [[UILabel alloc] initWithFrame:Label4Frame];
    lblTemp.tag = 4;
    lblTemp.text=[[stores objectAtIndex:row]objectAtIndex:5];   
    lblTemp.textAlignment=UITextAlignmentCenter;
    lblTemp.font = [UIFont systemFontOfSize:13];
    lblTemp.textColor = [UIColor grayColor ];
    [lblTemp setAdjustsFontSizeToFitWidth:YES];
    [cell.contentView addSubview:lblTemp];      
    [phoneButton release];
    [lblTemp release];  
    [cell setNeedsLayout];
    [cell setNeedsDisplay];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath ];   
    for(UILabel *lbl in cell.contentView.subviews){
        if([lbl isKindOfClass:[UILabel class]]){
            lbl.textColor=[UIColor whiteColor];

        }
    }
    //UITableViewCell *cell1;       
    //NSString *row=[NSString stringWithFormat:@"%d",indexPath.row];
    svm = [[storesMapView alloc] initWithNibName:@"storesMapView" bundle:nil];
    [svm initWithXML:stores:indexPath.row];
    CGRect theFrame = svm.view.frame;
    theFrame.origin = CGPointMake(self.view.frame.size.width, 0);
    svm.view.frame = theFrame;
    theFrame.origin = CGPointMake(0,0);
    theFrame.size=CGSizeMake(320,355);
    [UIView beginAnimations:nil context:nil]; 
    [UIView setAnimationDuration:0.3f];
    svm.view.frame = theFrame;
    [UIView commitAnimations];
    [subView addSubview:svm.view];
    backButton.hidden=NO;


}

Ответы [ 5 ]

19 голосов
/ 25 января 2011

Я понял это методом проб и ошибок;если это может помочь кому-то

В cellforRowAtIndexPath я попытался очистить все подпредставления ячеек перед тем, как нарисовать ячейку

//TRY TO REMOVE ALL CONTENT
    for(UIView *view in cell.contentView.subviews){
        if ([view isKindOfClass:[UIView class]]) {
            [view removeFromSuperview];
        }
    }

Я был бы рад, если бы кто-то мог указать мне на какой-то более простой способ

Спасибо

7 голосов
/ 05 августа 2011

Вы можете использовать

[[[cell contentView] subviews] makeObjectsPerformSelector: @selector(removeFromSuperview)];

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

for(UIView *eachView in [cell subviews])
    [eachView removeFromSuperview];
5 голосов
/ 15 мая 2013

У меня тоже была та же проблема. Я также создал tableView с метками. И когда я прокручивал его вниз, содержимое перекрывалось. Но это было решено простым редактированием одного оператора в cellForRowAtIndexPath.

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];

Я думаю, что это решит вашу проблему.

1 голос
/ 03 марта 2016

Установка nil для маркировки текста по методу подкласса UITableViewCell prepareForReuse () решила мою проблему -

  override func prepareForReuse() {
    super.prepareForReuse()
    self.label1.text = nil
    self.label2.text = nil
    ....
}

Поделись, если кому-нибудь поможет!

1 голос
/ 09 ноября 2011

Я знаю, что это немного поздно, но у меня была похожая проблема, когда UILabels, созданные для ячейки, были еще частью ячейки, когда она использовалась повторно.Таким образом, каждое последующее обновление табличного представления создавало еще одну UILabel поверх существующей.Я переместил создание меток в условие if, как показано ниже, и это решило мою проблему.Надеюсь, это поможет кому-то еще.Также обратите внимание на отсутствие выпуска, поскольку я использую ARC.

    static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) 

    {

    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    cityText = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 20)];
    cityText.font = [UIFont fontWithName:@"Arial" size:20];
    cityText.textAlignment = UITextAlignmentLeft; 
    cityText.backgroundColor = [UIColor clearColor];

    regionText = [[UILabel alloc] initWithFrame:CGRectMake(10, 40, 100, 20)];
    regionText.font = [UIFont fontWithName:@"Arial" size:20];
    regionText.textAlignment = UITextAlignmentLeft; 
    regionText.backgroundColor = [UIColor clearColor];

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