我正在使用viewController作爲使用Parse作爲後端的聊天室。 cellForRowAtIndexPath只爲最初可見的單元格調用(所以7或8次),然後當我向下滾動表格視圖時,空間在那裏,但它全部是空白的,cellForRowAtIndexPath不再被調用。數組的數量是正確的,所有的數據都被檢索。最容易混淆的部分是,有時它會在第一次加載時正常工作,然後在其他時間發生問題。先謝謝您的幫助。以下是我的tableView代理方法:cellForRowAtIndexPath在初始可見單元格被繪製後停止調用
#pragma mark - Table View Delegate Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.chatData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ChatCell *cell = (ChatCell *)[tableView dequeueReusableCellWithIdentifier:@"chatCellIdentifier"];
NSUInteger row = [self.chatData count]-[indexPath row]-1;
if (row < [self.chatData count]) {
NSString *chatText = [[self.chatData objectAtIndex:row] objectForKey:@"text"];
NSString *theUserName = [[self.chatData objectAtIndex:row] objectForKey:@"userName"];
PFFile *imageFile = [[self.chatData objectAtIndex:row] objectForKey:@"avatar"];
UIFont *font = [UIFont fontWithName:@"Arial" size:13.0];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:chatText attributes:attributes];
CGRect rect = [chatText boundingRectWithSize:CGSizeMake(225.0f, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:attributes
context:nil];
CGSize size = rect.size;
cell.textString.frame = CGRectMake(76, 23, size.width +20, size.height + 20);
cell.textString.textAlignment = NSLineBreakByWordWrapping;
NSDate *theDate = [[self.chatData objectAtIndex:row] objectForKey:@"date"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm a"];
NSString *timeString = [formatter stringFromDate:theDate];
cell.textString.attributedText = attrString;
[cell.textString sizeToFit];
cell.timeLabel.text = timeString;
cell.userLabel.text = theUserName;
cell.userAvatar.file = imageFile;
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellText = [[self.chatData objectAtIndex:self.chatData.count-indexPath.row-1] objectForKey:@"text"];
UIFont *cellFont = [UIFont fontWithName:@"Arial" size:13.0];
CGSize constraintSize = CGSizeMake(225.0f, MAXFLOAT);
CGRect boundingRect = [cellText boundingRectWithSize:constraintSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:[NSDictionary dictionaryWithObjectsAndKeys:cellFont, NSFontAttributeName, nil]
context:nil];
return boundingRect.size.height + 40;
}
在你調用dequeueReusableCellWithIdentifier之後,你需要確保它返回一個有效的單元格(cell == nil),否則你將不得不分配一個。 – rocky
@rocky,如果單元格是在故事板中製作的,或者您爲單元格註冊了一個班級或一個筆尖,則這不是必需的。此外,如果有必要分配單元格,那麼OP的代碼根本不會顯示任何單元格。 – rdelmar
該單元格是在一個帶有UITableViewCell子類的故事板中製作的。 – user1681673