1

我有一個非常可變的表格視圖,可以一次以多種方式由用戶編輯。添加,刪除行並在這些單元格內的文本字段中重命名文本。到目前爲止,我已經接入小區indexPath有:訪問表格視圖單元格中的某個對象位於:通過超級視圖訪問單元格的合法性?

-(void)textFieldDidEndEditing:(UITextField *)textField 
{ 
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:textField.tag inSection:0]; 
    MainCategory *mainCategory = [self.fetchedResultsController objectAtIndexPath:indexPath]; 

    if(textField.text != mainCategory.name){ 
     mainCategory.name = textField.text; 
    } 

    self.activeField = nil; 
} 

但是這給重新排序後,刪除等問題,現在用這種方法它的工作原理:

-(void)textFieldDidEndEditing:(UITextField *)textField 
{ 
    //NSIndexPath *indexPath = [NSIndexPath indexPathForRow:textField.tag inSection:0]; 

    // Get the cell in which the textfield is embedded 
    id textFieldSuper = textField; 
    while (![textFieldSuper isKindOfClass:[UITableViewCell class]]) { 
     textFieldSuper = [textFieldSuper superview]; 
    } 

    UITableViewCell *cell = textFieldSuper; 
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 
    MainCategory *mainCategory = [self.fetchedResultsController objectAtIndexPath:indexPath]; 

    if(textField.text != mainCategory.name){ 
     mainCategory.name = textField.text; 
    } 

    self.activeField = nil; 
} 

這是做一個合法的方式?

+0

是的,這是好的。 – Martol1ni

+0

是的,它不是問題。我曾多次使用superview kinda的東西。 – santhu

+0

好的..所以我擺脫了我所有的標籤..造成了很多問題...... THX! – MichiZH

回答

1

它會工作,但我更喜歡避免在不需要時使用循環。

您可以使用此解決方案:

-(void)textFieldDidEndEditing:(UITextField *)textField 
{ 
     CGPoint pnt = [self.tableView convertPoint:textField.bounds.origin fromView:textField]; 
     NSIndexPath* indexPath = [self.tableView indexPathForRowAtPoint:pnt]; 

     MainCategory *mainCategory = [self.fetchedResultsController objectAtIndexPath:indexPath]; 

     if(textField.text != mainCategory.name){ 
      mainCategory.name = textField.text; 
     } 

     self.activeField = nil; 
} 
相關問題