2012-10-01 39 views
1

我幾個小時以來一直非常困惑,所以我想現在是時候尋求幫助了!cellForRowAtIndexPath在自定義UITableViewCell的UITextField中有文本時返回null

我試圖訪問嵌入在UITableViewCell子類(QuestionCell)中的UITextField中的文本值。

問題是每當我嘗試使用cellForRowAtIndexPath方法訪問單元格時,它將返回(NULL)。

QuestionCell *qc = (QuestionCell*)[questionsTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; 
NSLog(@"qc %@",qc); // Gives "qc (NULL)" if there's text in the custom cell 

這僅如果有自定義單元格在UITextField輸入的文本發生。如果沒有文字,單元格將按預期返回。

我使用XCode4.2用故事板,自定義樣式和類爲UITableViewCell

這裏是我的QuestionCell.h

#import <UIKit/UIKit.h> 

@interface QuestionCell : UITableViewCell 


@property (weak, nonatomic) IBOutlet UILabel *correctionLabel; 
@property (weak, nonatomic) IBOutlet UIImageView *correctionMark; 
@property (weak, nonatomic) IBOutlet UILabel *pronounLabel; 
@property (weak, nonatomic) IBOutlet UITextField *answerInput; 

@end 

,細胞與通常的委託方法創建

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (indexPath.section == 0) 
    { 
     QuestionCell *cell = nil; 
     cell = [tableView dequeueReusableCellWithIdentifier:@"QuestionCell"]; 

     NSString *pronoun = nil; 

     switch (indexPath.row) { 
      case 0: 
       pronoun = @"je"; 
       break; 
      case 1: 
       pronoun = @"tu"; 
       break; 
      case 2: 
       pronoun = @"il"; 
       break; 
      case 3: 
       pronoun = @"nous"; 
       break; 
      case 4: 
       pronoun = @"vous"; 
       break; 
      case 5: 
       pronoun = @"ils"; 
       break; 
      default: 
       break; 
     } 

     cell.pronounLabel.text = pronoun; 

     return cell; 
    } 
    if (indexPath.section == 1) 
    { 
     ActionCell *cell = nil; 
     cell = [tableView dequeueReusableCellWithIdentifier:@"ActionCell"]; 
     return cell; 
    } 
    return nil; 
} 
+0

Hi Rob,非常感謝您回覆我。我的問題是,當鍵盤出現時,我的單元格離開了屏幕的頂部,因此我認爲問題在於我輸入了文本到單元格中。非常感謝你的幫助,非常感謝! –

回答

1

上述代碼沒有任何問題。我創建了一個測試項目,插入了這個QuestionCell(用UITextFieldUILabel對象完成)和你的tableView:cellForRowAtIndexPath,並且一切都很好。

UITableView方法cellForRowAtIndexPath只返回nil如果單元格已經滾動屏幕(這是預期的行爲)。但是有了這六個單元格,我遍歷了表格的`cellForRowAtIndexPath,並且一切都很好,無論我輸入了文本還是不輸入。

從您的後續評論來看,您的手機似乎已經從屏幕上滾動出來。是的,那肯定會導致cellForRowAtIndexPath返回nil

+0

查看cellForRowAtIndexPath的文檔:http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UITableView_Class/Reference/Reference.html#//apple_ref/occ/cl/UITableView沒有提到任何關於如果一個單元格不在屏幕上,則返回零。我有同樣的問題... – Sabobin

+1

@Sabobin在[「返回值」](http://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006943-CH3-SW16)部分,它表示「如果單元格不可見或者indexPath超出範圍,則表示表示單元格的表或nil的對象。 – Rob

+0

所以它!對不起,失明。 :) – Sabobin

相關問題