2015-01-06 4 views
-1

У меня есть пользовательский UITableViewCell, созданный в .xib и добавляющий его в TableView. Ячейка содержит кнопку для загрузки некоторых данных. На кнопке нажмите кнопку загрузки, и кнопка исчезнет, ​​чтобы отобразить кнопку отмены и пользовательский вид с прогрессом загрузки. После завершения загрузки я обновляю свою модель и перезаряжаю строки в видимой области приложения.После reloadRowsAtIndexPaths Пользовательский внешний вид UITableViewCell не изменяется

Когда я отлаживаю, я вижу, что cellForRowAtIndexPath-methode вызывается и модель обновляется. Это означает, что кнопка отмены и прогресс-вид становятся скрытыми = YES; Но они не исчезают. После того, как я прокручу ячейку вне поля зрения и снова, просмотр прогресса скрыт, но кнопка отмены недоступна.

TableView Methodes:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
static NSString *cellIdentifierHeaderCell = @"PodcastListHeaderCell"; 
static NSString *cellIdentifierBodyCell = @"PodcastListBodyCell"; 


// Convert string to date object 
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
[dateFormat setDateFormat:@"EEE, d MMM yyyy HH:mm:ss Z"]; 



if(indexPath.row == 0) { 
    MGPodcastListHeaderCell *cell = (MGPodcastListHeaderCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifierHeaderCell]; 
    if (cell == nil) 
    { 
      ... 

    } 
    return cell; 
} 
else { 
    MGPodcastListBodyCell *cell = (MGPodcastListBodyCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifierBodyCell]; 
    if (cell == nil) { 
     UIViewController *controller = [[UIViewController alloc] initWithNibName:@"MGPodcastListBodyCell" bundle:nil]; 
     cell = (MGPodcastListBodyCell *)controller.view; 
     NSMutableDictionary *mediaIntem = self.mediaData[(NSUInteger) (indexPath.row-1)]; 
     cell.mediaTitleLabel.text = mediaIntem[@"title"]; 
     NSDate *date = [dateFormat dateFromString:mediaIntem[@"pubDate"]]; 
     cell.pubDateLabel.text = [date descriptionWithLocale:[NSLocale currentLocale]]; 
     cell.durationLabel.text = mediaIntem [@"duration"]; 
     cell.accessoryType = UITableViewCellAccessoryDetailButton; 
     cell.podcastId = (NSInteger) (indexPath.row-1); 
     cell.cellPlayState = [[MGPlayState alloc] initWithPlayState:(NSInteger) [mediaIntem[@"playState"] integerValue]]; 
     [cell setPodcastCellDelegate:self]; 
    } 
    return cell; 
    } 
} 


-(void) downloadButtonPressedOfCell:(NSInteger)podcastId { 

APConnection *con = [[APConnection alloc] init]; 
BOOL reachable = [con reachableHost]; 
if (reachable) 
{ 


    //============Get Media Item ============================= 
    NSMutableDictionary *mediaDict = self.mediaData[(NSUInteger)podcastId]; 

    MGPlayState *pl_state = [[MGPlayState alloc] initWithPlayState:[[mediaDict objectForKey:@"playState"] integerValue]]; 

    NSString *urlString = [mediaDict objectForKey:@"mediaLink"]; 

    /// Finde Pathname 
    NSString *fileName = [urlString lastPathComponent]; 
    NSLog(@"LastFileComponent: %@", fileName); 
    NSString *pathName = [NSString stringWithFormat:@"%@/%@", 
                [APFilePath getMediaContentFolder], 
                fileName]; 

    /// Request und Operation 
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]; 
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:pathName 
                   append:NO]; 


    //// save Operation for cancle 
    NSMutableDictionary *operationDict = [[NSMutableDictionary alloc] init]; 
    [operationDict setObject:operation 
         forKey:@"operation"]; 
    [operationDict setObject:[NSNumber numberWithInt:podcastId] 
         forKey:@"myIndexPath"]; 
    [operationDict setObject:[mediaDict objectForKey:@"mediaLink"] 
         forKey:@"mediaLink"]; 

    [[self operationDictArr] addObject:operationDict]; 

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) 
      { 
       NSIndexPath *path = [NSIndexPath indexPathForRow:podcastId+1 inSection:0]; 
       MGPodcastListBodyCell *myCell = (MGPodcastListBodyCell *) [self.podcastListTable cellForRowAtIndexPath:path]; 

       [pl_state setToPlayState:PlayStateDefaultDownloadFinished]; 
       myCell.cellPlayState = pl_state; 


       //============ Get mediaItem ============================= 
       self.mediaData[(NSUInteger)podcastId][@"playState"] = @4; 


       /// remove operation from dict 
       [[self operationDictArr] removeObject:operationDict]; 

       [self.podcastListTable reloadRowsAtIndexPaths:[self.podcastListTable indexPathsForVisibleRows] 
           withRowAnimation:UITableViewRowAnimationNone]; 
       [self.podcastListTable setNeedsDisplay]; 
      } 
            failure:^(AFHTTPRequestOperation *operation, NSError *error) 
            { 
             NSLog (@"Error downloadMovie: %@", error); 
            }]; 

    [operation start]; 

} 

else 
{ 
    [EZToastView showToastMessage:NSLocalizedString(@"keineVerbindungKey", "") 
        withAlignment:EZToastViewAlignmentCenter]; 
} 
} 

Пользовательские Cell:

//// MGPodcastListBodyCell.h 
@protocol MGPodcastCellDelegate <NSObject> 
@required 
-(void) downloadButtonPressedOfCell: (NSInteger) podcastId; 
-(void) cancleDownloadButtonPressedOfCell: (NSInteger) podcastId; 
@end 


@interface MGPodcastListBodyCell : UITableViewCell 
@property (nonatomic, retain) id <MGPodcastCellDelegate> podcastCellDelegate; 
@property (weak, nonatomic) IBOutlet UILabel *mediaTitleLabel; 
@property (weak, nonatomic) IBOutlet UILabel *durationLabel; 
@property (weak, nonatomic) IBOutlet UIButton *downloadMediaButton; 
@property (weak, nonatomic) IBOutlet UIButton *cancelMediaDownloadButton; 
@property (weak, nonatomic) IBOutlet MGProgressDownloadView *progressDownloadView; 
@property (weak, nonatomic) IBOutlet UILabel *pubDateLabel; 
@property (strong, nonatomic) MGPlayState *cellPlayState; 
@property (nonatomic) NSInteger podcastId; 

- (IBAction) downloadButtonPressed:(UIButton *)sender; 
- (IBAction) cancleMediaDownloadButonPressed:(UIButton *)sender; 
@end 



//MGPodcastListBodyCell.m 
@implementation MGPodcastListBodyCell 

@synthesize cellPlayState = _cellPlayState; 

- (void)setCellPlayState:(MGPlayState *) cellPlayState { 
    _cellPlayState = cellPlayState; 
    [self playStateChanged]; 
} 


- (void)awakeFromNib { 
    [self setup]; 
} 

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) { 
     [self setup]; 
    } 
    return self; 
} 

- (void)setup 
{ 
    UIView *customBackgroundView = [[UIView alloc] init]; 
    customBackgroundView.backgroundColor = [APAppearence sharedInstance].tableCellBackgroundColorMB; 
    self.backgroundView = customBackgroundView; 

    self.mediaTitleLabel.textColor = [APAppearence sharedInstance].tableCellMainlabelTextColorMB; 
    self.durationLabel.textColor = [APAppearence sharedInstance].standardDarkGrayColorMB; 
    self.tintColor = [APAppearence sharedInstance].tableCellMainlabelTextColorMB; 

    [self playStateChanged]; 
} 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated { 
    [super setSelected:selected animated:animated]; 

    // Configure the view for the selected state 
} 

- (void) playStateChanged { 
    self.downloadMediaButton.hidden = self.cellPlayState.playButtonHidden; 
    [self.downloadMediaButton setNeedsDisplay]; 
    self.cancelMediaDownloadButton.hidden = self.cellPlayState.cancelButtonHidden; 
    [self.cancelMediaDownloadButton setNeedsDisplay]; 
    self.progressDownloadView.hidden = self.cellPlayState.progressViewHidden; 
    [self setNeedsDisplay]; 
} 

- (IBAction) downloadButtonPressed:(UIButton *)sender { 
    [self.podcastCellDelegate downloadButtonPressedOfCell: self.podcastId]; 
} 
- (IBAction) cancleMediaDownloadButonPressed:(UIButton *)sender { 
    [self.podcastCellDelegate cancleDownloadButtonPressedOfCell: self.podcastId]; 
} 

@end 

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

ответ

0

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

MGPodcastListBodyCell *cell = (MGPodcastListBodyCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifierBodyCell]; 
if (cell == nil) { 
    .... 
} 

В вашем методе - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ . Поскольку ячейка повторно используется, то cell не будет равно нулю во второй раз и поэтому не обновляется никакой новой информацией.

Вам нужно что-то сделать, когда cell не является нулевым, чтобы его обновить.

+0

Большое спасибо за ваш ответ. Когда я отлаживаю, отладчик переходит в if-statement. Поэтому я думал, что клетка нуль. Но тем не менее я прокомментировал dequeueReusableCellWithIdentifier, поэтому каждый раз, когда создавалась новая ячейка (если я не ошибаюсь). Но это ничего не значит. Я что-то понимаю неправильно? – Maja

+0

Вы всегда должны использовать dequeueResuable, где можете, так как это помогает в производительности. Если вы говорите, что его никогда не повторное использование, это не проблема – Flexicoder

0

Я нашел ошибку. Это не проблема с методом reloadRowAtIndexPath. Это была проблема параллелизма. Состояние завершения загрузки было перезаписано потоком выполнения загрузки только в конце загрузки, и состояние было настроено обратно для загрузки.

Итак, спасибо вам всем за вашу помощь.