2013-02-06 32 views
2

我使用tableview和可重用單元格。在每個單元上我都有一個帶有文本的textField,我可以修改它。如果文本爲空,則刪除該單元格。使用cellForRowAtIndexPath修改現有的可重用單元格:方法

比方說,我們有100行,我們要修改的行數1:我們敲擊它,給一個空字符串@「」,向下滾動到位置號碼50並點擊該小區。

現在所要的是,我們發現輕拍手勢另一個單元格和我打電話的方法textFieldDidEndEditing:看我應該從tableview中刪除該小區。我使用cellForRowAtIndexPath:獲取修改後的單元格。

的問題是,似乎有其他細胞的空文本域。我刪除了修改後的單元格,但只有一個。我認爲這是可重複使用的單元的問題。

能有人能幫助我解決這個問題?

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

    StandardCellWithImage *cellImage = (StandardCellWithImage *)[tableView dequeueReusableCellWithIdentifier:ImageIdentyfier]; 

    if(cellImage == nil) { 
     cellImage = [[StandardCellWithImage alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ImageIdentyfier]; 
    } 
    cellImage.nameLabel.delegate = self; 
    Item *item = [self.mutableFetchResults objectAtIndex:indexPath.row]; 
    cellImage.nameLabel.text = item.itemText; 
    cellImage.infoLabel.text = item.itemInfo; 
    cellImage.checkbox.userInteractionEnabled = YES; 
    cellImage.nameLabel.userInteractionEnabled = NO; 
    if(item.itemIsChecked.boolValue == YES) { 
     cellImage.checkbox.tag = indexPath.row; 
     [cellImage.tapGesture addTarget:self action:@selector(didSelectedImageAtIndexPath:)]; 
     cellImage.checkbox.image = [UIImage imageNamed:@"checkbox-checked.png"]; 
    } else { 
     cellImage.checkbox.tag = indexPath.row; 
     [cellImage.tapGesture addTarget:self action:@selector(didSelectedImageAtIndexPath:)]; 
     cellImage.checkbox.image = [UIImage imageNamed:@"open-checkbox.png"]; 
    } 
    return cellImage; 
} 
+1

請張貼一些代碼。但無論如何,最好的辦法是將模型(文本字段的數據)和視圖(單元格與文本字段)分開,保持模型與數據更改保持一致,並且每次從模型中加載單元格。 – Mohammad

+0

通用評論:嘗試刪除nameLabel.delegate並使用標記和tapGesture。你會遇到與每個問題,嘗試使用didSelectRowAtIndexPath和cellForRowAtIndexPath獲得相同的功能 – JOM

回答

1

當您從第1行滾動到第50行時,已經存在的單元格將被重用 - 包括您的單元格爲空textField。這就是爲什麼你多次看到它,以及爲什麼你的刪除例程只刪除一個而不是全部。

聽起來像是在cellForRowAtIndexPath方法你的創作需要修理,以確保空的文本框不會自動複製到再生細胞。沒有看到任何代碼,這個練習是給你的。

看着代碼,thanx。無法看到任何「簡單」修復,因此建議您應該避免問題。因此,而不是檢查單元格水龍頭,也許你應該檢查列表滾動。

不僅是因爲細胞,這是被編輯,被回收,由於用戶滾動列表中你有這個問題存在。因此,通過a)不要讓用戶在編輯文本時滾動或者b)當用戶開始滾動時停止文本編輯。

+0

感謝JOM,你可以消化我如何解決自動重用textField的問題? – edzio27

+0

Thanx代碼,更新我的回答 – JOM

+0

這是非常有益的,它的解決方案與resignFirstResponder,而滾動使我的代碼工作。謝謝! – edzio27

0

當你textFieldDidEndEditing調用完成,您應檢查文本是否是""如果是""我想你應該從dataSource刪除它,然後reloadData

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法應該這樣寫:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    XXXXXXXCell *cell = [tableView dequeueReusableCellWithIdentifier: kIdentifier : 
    if (cell == nil) { 

     //init cell , only init 

    } 

    //setup the cells detail , such as the textField.text and so on 

    return cell; 

} 
相關問題