2015-07-21 60 views
0

我有一個UITableView,它有一個自定義UITableViewCell,其中有一個UITextFieldUITableViewCell中的UITextField - 重用問題

每個UITextField顯示一些文本從我的viewModel和我使用Reactive-Cocoa將文本字段綁定到viewModel

當我的UITableView第一次加載時,一切正常。但是,當我爲下一個'頁面'重新加載UiTableView - 第一個UiTextField重新加載(頁面2)時,tableView與第一個'頁面'中的第一個UITextField具有完全相同的內存地址 - 單元格與其他UI元素不同正確 - 只是文本字段是相同的實例。

因此,我宣佈UITextField在我的VC像這樣:

@property (weak, nonatomic) UITextField *textFieldOne; //One the first 'page' 
@property (weak, nonatomic) UITextField *textFieldTwo; //After reload on second 'page' 

然後設置,然後像這樣由cellForRowAtIndexPath

-(void)configureTextFieldCell:(BBTextFieldLabelTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath 
    { 
     cell.textField.delegate = self; 

     if (self.selectedSegmentIndex == SegmentedControlStep1){ 
      if (indexPath.section == 0){ 

          cell.label.text = @"Name"; 
          self.textFieldOne = cell.textField; 
        } 
       /* Code for setting up other cells/textfields ommited - 
       but the same syntax as above with checks for indexPath */ 
       } 

     if (self.selectedSegmentIndex == SegmentedControlStep2){ 

       cell.label.text = @"Username"; 
       self.textFieldTwo = cell.textField; 

      [self bindUsernameAndPasswordToViewModel]; /* Binding for this textfield as its nil when VC loads for the first time, 
                  so this is the first chance I get to bind it on second page */ 
     } 
    } 

援引內部BBTextFieldLabelTableViewCellUITextField的方法聲明如下所以:

@property (strong, nonatomic) IBOutlet UITextField *textField; 

我也試過在單元的執行文件裏面這樣做:

-(void)prepareForReuse 
{ 
    self.textField = [[UITextField alloc] init]; 
} 

正如我以爲我的問題可能是某種細胞重用問題。 但是,這段代碼沒有任何區別。

所以textFieldOnetextFieldTwo都有完全相同的內存地址,我不明白爲什麼。

裏面cellForRowAtIndexPath我創建單元格像這樣:

BBTextFieldLabelTableViewCell *textFieldCell = [tableView dequeueReusableCellWithIdentifier:textFieldCellidentifier]; 
+0

你檢查了單元的內存地址嗎? –

+0

有趣的...地址是相同的,在某些情況下,UI元素是不正確的。看起來好像UITableView重複使用確切的單元格,而不是正確地更新內容。任何想法如何我可以解決這個問題? – Tander

+0

如果目的和用戶界面不同,您可以爲第二個屏幕創建不同的自定義單元格。 –

回答

1

在你prepareForReuse要創建一個新的文本字段,但你既不移除舊,也不添加新的。

我建議使用prepareForReuse重置當前文本字段,而不是多一點精心打造一個新的

讀你的問題:事實上,文本域一和二都具有相同的價值,表明備再用不會在對configureTextFieldCell的兩次調用之間調用。沒有更多的代碼,很難理解爲什麼

+0

只需檢查;正在調用prepareForReuse。我也改變它重置textField而不是創建一個新的。不過,我仍然有問題,在tableView重新使用錯誤的單元格。 cellForRowAtIndexPath只是調用configureTextFieldCell - 沒有什麼特別的。我已經通過創建單元格更新了我的問題。 – Tander

+0

@Tander你是什麼意思是由tableView重用錯誤的單元格。你的意思是重複使用的單元格的舊內容沒有清除? – SFF

+0

@SFF是的,就是這樣。然而,採取亞瑟的建議似乎已經修復了一些事情,因爲我不再看到這個錯誤。我希望我知道爲什麼。如果我找出導致它的原因,將更新問題與答案。 – Tander