Ответ 1
Очевидно, проблема заключалась в том, что tableView еще не был настроен, когда я запросил ячейку.
Я пытаюсь получить определенную ячейку из представления таблицы, чтобы я мог изменить ее метку и остановить индикатор активности.
Проблема, с которой я столкнулась, заключается в том, что cellForRowAtIndexPath
возвращает nil.
В моем представлении таблицы есть только 1 строка.
Код:
- (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;
}
Однако, если я делаю что-то подобное, я получаю действительную ячейку:
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";
Любая идея, как это исправить? (Может быть, первая ячейка по умолчанию не находится в строке 0 раздела 0?)
Очевидно, проблема заключалась в том, что tableView еще не был настроен, когда я запросил ячейку.
Стоит отметить, что cellForRowAtIndexPath: также возвращает nil, если ячейка не видна.
Это может быть особенно актуально при потоковом...
У меня было cellForRowAtIndexPath
, возвращающее нуль, и причиной для меня было то, что я вызывал его в методах, когда UITableView не должен был полностью инициализироваться и заполняться. Как только я переместил свой вызов на cellForRowAtIndexPath
в -(void)viewDidAppear:(BOOL)animated
, тогда моя ячейка вернулась правильно.
Я столкнулся с той же проблемой, cellForRowAtIndexPath возвращает нуль и по довольно глупым причинам. В tableView:cellForRowAtIndexPath:
я вызвал метод, который вызвал метод, который вызывает [self.tableView cellForRowAtIndexPath:indexPath]
. (Повторное использование существующего кода и перемещение некоторой логики вниз по течению.)
Как оказалось, ячейка еще не доступна для возврата cellForRowAtIndexPath:
. Вы либо должны сделать все свое дело, модифицируя ячейку в tableView:cellForRowAtIndexPath:
, или, я полагаю, передаем *cell
.
У меня с вами очень схожее состояние, но я решил эту проблему, назвав функцию "супер", а не self.tableView. Я не знаю, почему, но это работает как минимум. Возможно, вы можете попробовать.
[super tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
вы решили вопрос, хотя я столкнулся с подобной ситуацией, поэтому, что я сделал, я показываю вам:
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;
}
}
странно, но хорошо работает после нескольких часов проб и ошибок.
Попробуйте использовать:
[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];
Попробуйте переопределить:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}