ios cellForRowAtIndexPath 返回 nil

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5232849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 19:10:13  来源:igfitidea点击:

cellForRowAtIndexPath returns nil

iphoneiosuitableview

提问by Idan

I'm trying to get a specific cell from a table view so I can change it's label and stop the activity indicator.

我正在尝试从表格视图中获取特定单元格,以便我可以更改它的标签并停止活动指示器。

The problem I'm having is that cellForRowAtIndexPathreturns nil.

我遇到的问题是cellForRowAtIndexPath返回零。

My table view has only 1 row.

我的表视图只有 1 行。

Code :

代码 :

- (id) initWithNibName: (NSString*) nibNameOrNil bundle: (NSBundle*) nibBundleOrNil
{
    self = [super initWithNibName: nibNameOrNil bundle: nibBundleOrNil];

    if (self) 
    {
        numberOfRows = 1;
    }

    return self;
}

- (NSInteger) tableView: (UITableView*) tableView numberOfRowsInSection: (NSInteger) section
{
    return numberOfRows;
}

-(void) stopCellIndicator
{

    LiveUserFeedCell* cell = (LiveUserFeedCell*)[self.liveFeed cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];  
    [cell.activityIndicator stopAnimating];
    cell.middleLabel.text = @"N/a";
}

- (UITableViewCell*) tableView: (UITableView*) tableView cellForRowAtIndexPath: (NSIndexPath*) indexPath
{
    static NSString *CellIdentifier = @"UserFeedCell";


    LiveUserFeedCell *cell = (LiveUserFeedCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"LiveUserFeedCell" owner:self options:nil];
        cell = (LiveUserFeedCell *)[nib objectAtIndex:0];
    }

    [cell.imgView setImage:[TUNinePatchCache imageOfSize:cell.imgView.frame.size forNinePatchNamed:@"bg_home_newsfeed_normal"]];


    if (shouldDisplayLoading == NO)
    {
        NSArray* songs = homeScreen.recentPlaybacks.songs;
        TWSong* song = [songs objectAtIndex:index];
        cell.middleLabel.text = @"";
        [cell.activityIndicator stopAnimating];

        UIFont *font = [UIFont fontWithName:@"Trebuchet MS" size:14];                       

        NSString* kText =[NSString stringWithFormat:@"<b>%@</b> is listening to %@ by %@",song.user,song.title,song.artist];

        for(int i = 14; i > 0; i=i-1)
        {
            // Set the new font size.
            font = [font fontWithSize:i];
            // You can log the size you're trying: NSLog(@"Trying size: %u", i);

            /* This step is important: We make a constraint box 
             using only the fixed WIDTH of the UILabel. The height will
             be checked later. */ 
            CGSize constraintSize = CGSizeMake(cell.isWatching.frame.size.width, MAXFLOAT);

            // This step checks how tall the label would be with the desired font.
            CGSize labelSize = [kText sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

            /* Here is where you use the height requirement!
             Set the value in the if statement to the height of your UILabel
             If the label fits into your required height, it will break the loop
             and use that font size. */
            if(labelSize.height <= cell.isWatching.frame.size.height)
                break;
        }



        cell.isWatching.font = font;
        cell.isWatching.text = [TTStyledText textFromXHTML:kText lineBreaks:YES URLs:YES];
        cell.isWatching.textAlignment = UITextAlignmentCenter;

        ++index;
        if (index == [songs count])
            index=0;

    }
    else
    {       
        [cell.activityIndicator startAnimating];
    }

    return cell;
}

However, if I do something like this, I do get a valid cell:

但是,如果我做这样的事情,我会得到一个有效的单元格:

NSArray *indexPaths = [NSArray arrayWithObjects: 
                       [NSIndexPath indexPathForRow:0 inSection:0],
                       nil];

numberOfRows = 0;
[self.liveFeed deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft];


numberOfRows = 1;
[self.liveFeed insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationRight];

LiveUserFeedCell* cell = (LiveUserFeedCell*)[self.liveFeed cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];  
[cell.activityIndicator stopAnimating];
cell.middleLabel.text = @"N/a";

Any idea how to fix this? (Maybe the default first cell isn't in row 0 section 0?)

知道如何解决这个问题吗?(也许默认的第一个单元格不在第 0 行第 0 部分?)

采纳答案by Idan

Apparently the problem was that the tableView was not configured yet when I queried the the cell.

显然问题是当我查询单元格时 tableView 尚未配置。

回答by Andres Canella

It is worth mentioning that cellForRowAtIndexPath: will also return nil if the cell is not visible.

值得一提的是,如果单元格不可见, cellForRowAtIndexPath: 也会返回 nil。

This can especially be an issue when threading...

这在线程处理时尤其是一个问题......

回答by Stephen Watson

I was having cellForRowAtIndexPathreturning nil and the cause of it for me was that I was calling it in methods where the UITableView must not have been fully initialised and filled. Once I'd moved my call to cellForRowAtIndexPathinto -(void)viewDidAppear:(BOOL)animatedthen my cell was returned correctly.

我正在cellForRowAtIndexPath返回 nil ,对我来说它的原因是我在 UITableView 必须没有完全初始化和填充的方法中调用它。一旦我将我的电话转到cellForRowAtIndexPath了,-(void)viewDidAppear:(BOOL)animated我的手机就被正确返回了。

回答by DavGarcia

I ran into the same issue, cellForRowAtIndexPath returning nil, and for rather silly reasons. In tableView:cellForRowAtIndexPath:I called a method which called method which calls [self.tableView cellForRowAtIndexPath:indexPath]. (Was reusing existing code, and moving some logic downstream.)

我遇到了同样的问题, cellForRowAtIndexPath 返回 nil,并且出于相当愚蠢的原因。在tableView:cellForRowAtIndexPath:我调用了一个调用方法的方法,该方法调用了[self.tableView cellForRowAtIndexPath:indexPath]. (正在重用现有代码,并将一些逻辑移到下游。)

As it turns out, the cell isn't yet available for cellForRowAtIndexPath:to return. You either need to do all your business modifying the cell in tableView:cellForRowAtIndexPath:or, I guess, pass the *cellalong.

事实证明,该单元格还不能cellForRowAtIndexPath:返回。您要么需要完成所有修改单元格的工作,tableView:cellForRowAtIndexPath:要么我想,传递*cell下去。

回答by Christopher

I got very similar condition with you, but I solved this problem by calling "super" function rather than self.tableView. I don't know why but it works at least. Maybe you can try.

我和你的情况非常相似,但我通过调用“超级”函数而不是 self.tableView 解决了这个问题。我不知道为什么,但它至少有效。也许你可以试试。

[super tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];

回答by harshalb

you have solved the question though I have faced similar situation so what I have done I am showing you :

尽管我遇到了类似的情况,但您已经解决了这个问题,所以我向您展示了我所做的:

NSArray *cells = [contactsTable visibleCells];

    UITableViewCell *cell = nil;
    NSIndexPath *path = [param objectAtIndex:1];
    for (UITableViewCell *aCell in cells) {
        NSIndexPath *aPath = [contactsTable indexPathForCell:aCell];

        if ([aPath isEqual:path]) {
            cell = aCell;
        }
    }

weird but works good after hours of trial & error.

很奇怪,但经过数小时的反复试验后效果很好。

回答by Schoob

Try using:

尝试使用:

[self.livFeed beginUpdates];   
LiveUserFeedCell* cell = (LiveUserFeedCell*)[self.liveFeed cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];  
[cell.activityIndicator stopAnimating];
cell.middleLabel.text = @"N/a";
[self.liveFeed endUpdates];

Apple UITableView doc

苹果 UITableView 文档