How to get a UITableViewCell from one of its subviews

前端 未结 4 1805
野性不改
野性不改 2020-12-17 16:39

I have a UITableView with a UITextField in each of the UITableViewCells. I have a method in my ViewController which handles the \"Did

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-17 17:10

    Basically in this case, I would prefer you to put the IBAction method into cell instead of view controller. And then when an action is triggered, a cell send a delegate to a view controller instance.

    Here is an example:

    @protocol MyCellDelegate;
    
    
    @interface MyCell : UITableViewCell
    
    @property (nonatomic, weak) id delegate;
    
    @end
    
    @protocol MyCellDelegate 
    
    - (void)tableViewCell:(MyCell *)cell textFieldDidFinishEditingWithText:(NSString *)text;
    
    @end
    

    In a implementation of a cell:

    - (IBAction)itemFinishedEditing:(UITextField *)sender
    {
        // You may check respondToSelector first
        [self.delegate tableViewCell:self textFieldDidFinishEditingWithText:sender.text];
    }
    

    So now a cell will pass itself and the text via the delegate method.

    Suppose a view controller has set the delegate of a cell to self. Now a view controller will implement a delegate method.

    In the implementation of your view controller:

    - (void)tableViewCell:(MyCell *)cell textFieldDidFinishEditingWithText:(NSString *)text
    {
        NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
        _list.items[indexPath.row] = text;
    }
    

    This approach will also work no matter how Apple will change a view hierarchy of a table view cell.

提交回复
热议问题