How to get a UITableViewCell from one of its subviews

前端 未结 4 1807
野性不改
野性不改 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 16:59

    You can attach the UITableViewCell itself as a weak association to the UITextField, then pluck it out in the UITextFieldDelegate method.

    const char kTableViewCellAssociatedObjectKey;
    

    In your UITableViewCell subclass:

    - (void)awakeFromNib {
        [super awakeFromNib];
        objc_setAssociatedObject(textField, &kTableViewCellAssociatedObjectKey, OBJC_ASSOCIATION_ASSIGN);
    }
    

    In your UITextFieldDelegate method:

    UITableViewCell *cell = objc_getAssociatedObject(textField, &kTableViewCellAssociatedObjectKey);
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    //...
    

    I'd also recommend re-associating every time a cell is dequeued from the UITableView to ensure that the text field is associated with the correct cell.

提交回复
热议问题