Recipes to pass data from UITableViewCell to UITableViewController

前端 未结 2 1899
天涯浪人
天涯浪人 2021-01-14 16:40

I\'m figuring out the right mechanism to pass data from UITableViewCells to a UIableViewController (or UIViewController).

Sear

相关标签:
2条回答
  • 2021-01-14 17:05

    Why not just use [UITableView indexPathForCell:] with a delegate?

    MyViewController.h

    @interface MyViewController : UITableViewController <MyTableViewCellDelegate>
    
    @end
    

    MyViewController.m

    @implementation MyViewController
    
    // methods...
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
       NSString *reuseIdentifier = @"MyCell";
       MyTableViewCell *cell = (id)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    
       if (cell == nil)
           cell = [[[MyTableViewCell alloc] initWithMyArgument:someArgument reuseIdentifier:reuseIdentifier] autorelease];
    
        [cell setDelegate:self];
    
        // update the cell with your data
    
        return cell;
    }
    
    - (void)myDelegateMethodWithCell:(MyTableViewCell *)cell {
    
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
        // update model
    }
    
    @end
    

    MyTableViewCell.h

    @protocol MyTableViewCellDelegate;
    
    @interface MyTableViewCell : UITableViewCell
    
    @property (assign, nonatomic) id <MyTableViewCellDelegate> delegate;
    
    - (id)initWithMyArgument:(id)someArgument reuseIdentifier:(NSString *)reuseIdentifier;
    
    @end
    
    
    @protocol MyTableViewCellDelegate <NSObject>
    
    @optional
    
    - (void)myDelegateMethodWithCell:(MyTableViewCell *)cell;
    
    @end
    

    MyTableViewCell.m

    @implementation MyTableViewCell
    
    @synthesize delegate = _delegate;
    
    - (id)initWithMyArgument:(id)someArgument reuseIdentifier:(NSString *)reuseIdentifier {
    
        self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    
        if (self) {
            // custom setup
        }
    
        return self;
    }
    
    - (void)prepareForReuse {
        [super prepareForReuse];
    
        self.delegate = nil;
    }
    
    - (void)someActionHappened {
    
        if ([self.delegate respondsToSelector:@selector(myDelegateMethodWithCell:)])
            [self.delegate myDelegateMethodWithCell:self];
    }
    
    @end
    
    0 讨论(0)
  • 2021-01-14 17:16
    1. To modify cells you should modify data model and reload table data. Nothing else.
    2. Not necessary to have a indexPath for cell
    3. In your case it is the same using retain or copy policy. Copy makes new objects with same state.
    0 讨论(0)
提交回复
热议问题