2013-06-19 3 views
0

Я пытаюсь добавить таймер на стороне эскиза, но UIlabel для таймера всегда дублируется при прокрутке.Этикетки дублирующие?

Это заканчивается следующим образом. Любая помощь будет принята с благодарностью.

http://gyazo.com/0d22d9e3adc0ecbbacd8cb2cdb59d8b4.png

Это как мой метод выглядит

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

    static NSString *CellIdentifier = @"Cell"; 
    ChanelFeeds *currentFeed = [[xmlParser feeds] objectAtIndex:indexPath.row]; 

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

     CGRect imageFrame = CGRectMake(0, 0, 120, 90); 
     self.customImage = [[UIImageView alloc] initWithFrame:imageFrame]; 
     [cell.contentView addSubview:self.customImage]; 
     [self.customImage release]; 

     // Title 
     CGRect contentFrame = CGRectMake(122, 2, 198, 45); 
     UILabel *title = [[UILabel alloc] initWithFrame:contentFrame]; 
     title.tag = 0011; 
     title.numberOfLines = 2; 
     title.backgroundColor = [UIColor clearColor]; 
     title.textColor = [UIColor whiteColor]; 
     title.font = [UIFont boldSystemFontOfSize:14]; 
     [cell.contentView addSubview:title]; 
     [title release]; 

     // Views Placement 
     CGRect contentFrame2 = CGRectMake(127, 70, 180, 15); 
     UILabel *title2 = [[UILabel alloc] initWithFrame:contentFrame2]; 
     title2.tag = 0012; 
     title2.numberOfLines = 1; 
     title2.backgroundColor = [UIColor clearColor]; 
     title2.textColor = [UIColor whiteColor]; 
     title2.font = [UIFont italicSystemFontOfSize:14]; 
     [cell.contentView addSubview:title2]; 
     [title2 release]; 



     //Here's where the fails come in 


     CGRect contentFrame6 = CGRectMake(0, 66, 33, 13); 
     CGRect contentFrame7 = CGRectMake(6, 65, 60, 15); 
     UIImageView *imv5 = [[UIImageView alloc]initWithFrame:contentFrame6]; 
     UILabel *title3 = [[UILabel alloc] initWithFrame:contentFrame7]; 
     imv5.alpha = 1; 
     title3.tag = 0013; 
     imv5.tag = 0014; 
     [cell.contentView addSubview:imv5]; 
     imv5.backgroundColor = [UIColor clearColor]; 


    } 

    // Formatting views 
    NSNumberFormatter * f = [[NSNumberFormatter alloc] init]; [f setNumberStyle:NSNumberFormatterDecimalStyle]; NSNumber * formattedViews = [f numberFromString 
    :[currentFeed views]]; [f release]; NSNumber *firstNumber = formattedViews; NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];[formatter setNumberStyle: NSNumberFormatterDecimalStyle]; convertedNumber = [formatter stringForObjectValue:firstNumber]; 


    // Basic stuff 
    UILabel *title = (UILabel *)[cell.contentView viewWithTag:0011]; 
    UILabel *title2 = (UILabel *)[cell.contentView viewWithTag:0012]; 
    UILabel *title3 = (UILabel *)[cell.contentView viewWithTag:0013]; 

    title.text = [currentFeed title]; 
    title2.text = [NSString stringWithFormat:@"%@ views", convertedNumber]; 


    totalTime = [self timeFormatted:([currentFeed duration].intValue)-1]; 
    NSString *word = @":00:"; 
    if ([totalTime rangeOfString:word].location == NSNotFound) { 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"00:" withString:@""]; 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"01:" withString:@"1:"]; 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"02:" withString:@"2:"]; 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"03:" withString:@"3:"]; 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"04:" withString:@"4:"]; 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"05:" withString:@"5:"]; 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"06:" withString:@"6:"]; 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"07:" withString:@"7:"]; 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"08:" withString:@"8:"]; 
     totalTime = [totalTime stringByReplacingOccurrencesOfString:@"09:" withString:@"9:"];} 
    if([totalTime length] >= 5) { 
     CGRect contentFrame7 = CGRectMake(4, 65, 60, 15); 
     title3 = [[UILabel alloc] initWithFrame:contentFrame7]; 
     title3.textColor = [UIColor whiteColor]; 
     title3.backgroundColor = [UIColor clearColor]; 
     title3.font = [UIFont boldSystemFontOfSize:10]; 
    } else { 
     CGRect contentFrame7 = CGRectMake(6, 65, 60, 15); 
     title3 = [[UILabel alloc] initWithFrame:contentFrame7]; 
     title3.textColor = [UIColor whiteColor]; 
     title3.backgroundColor = [UIColor clearColor]; 
     title3.font = [UIFont boldSystemFontOfSize:10]; 

    } 
    title3.text = totalTime; 
    [cell.contentView addSubview:title3]; 



    NSString *directoryPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
    NSURL *imgURL = [currentFeed thumbnailURL]; 
    NSArray *parts = [[NSString stringWithFormat:@"%@", imgURL] componentsSeparatedByString:@"/"]; 
    NSString *imageName = [parts objectAtIndex:[parts count]-2]; 

    NSString *filePath = [directoryPath stringByAppendingPathComponent:imageName]; 

    UIImage *myview = [UIImage imageWithContentsOfFile:filePath]; 
    if(myview){ 
     cell.imageView.image = myview; 

     //Add Black fucking border and stuff here!!! 
    }else{ 


     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
      NSData* data = [NSData dataWithContentsOfURL:[currentFeed thumbnailURL]]; 
      UIImage *thumbnail = [UIImage imageWithData:data]; 
      cell.imageView.image = thumbnail; 
      [self.feedsTableView beginUpdates]; 
      [self.feedsTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] 
             withRowAnimation:UITableViewRowAnimationNone]; 
      [self.feedsTableView endUpdates]; 


     }); 
    } 

    return cell; 
} 
+0

Ручное форматирование @ "00", @ "01" и т. Д., А также обновление пользовательского интерфейса из фонового потока. У вас нет стыда? – Abizern

+0

@ Абизерн Он, очевидно, новичок. Ручное форматирование ужасно с точки зрения качества кода, но это не совсем неправильно. Однако фоновый поток, особенно вызванный этим методом, является очень неправильной задачей. – Sulthan

+0

Что еще я мог сделать, например? – IamGretar

ответ

2

Очевидные:

Не добавлять любые мнения вне (cell == nil) блока.

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

Есть много других проблемных частей. Например, перезагрузка ячеек внутри этого метода ОЧЕНЬ странная.

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

+0

Тогда ничего не появляется? http://gyazo.com/577fc442b551b97e2ab25552cb2c32ca.png – IamGretar

+0

@IamGretar Первая версия моего ответа была неправильной. – Sulthan

+0

Спасибо, что я добавил все внутри блока (cell == nil) и, похоже, работает. – IamGretar

Смежные вопросы