kubo
kubo

Reputation: 492

UITableViewCell from contentView subview

I have created the cells with labels and using checkaMarksAccessory. The few last cells have UITextFields which can user modifi, and those have selector on UIControlEventEditingDidEnd where i want change the state of the cell to checked.

How can i get the cell in the selector? Doesn't have the object some parentView?

The way i inserting the object to cell.

    UITextField *textfield = [[UITextField alloc] initWithFrame:CGRectMake(10, 25, 200, 30)];
    [textfield setBorderStyle:UITextBorderStyleRoundedRect];
    [textfield addTarget:self action:@selector(vybavaDidFinishEdit:) forControlEvents:UIControlEventEditingDidEnd];
    [cell.contentView addSubview:textfield];

Upvotes: 1

Views: 1879

Answers (2)

ma11hew28
ma11hew28

Reputation: 126507

I'm not sure if it's safe to assume cell.contentView.superview == cell. Might Apple change this? I doubt it. But, I don't see anywhere in the documentation that says a cell's content view is a direct subview of the cell.

If you've added a UIGestureRecognizer to one of your subviews of the cell's content view, then you can get a reference to the cell with:

NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:[gestureRecognizer locationInView:self.tableView]];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];

Table View Animations and Gestures sample code uses indexPathForRowAtPoint: this way.

If you must traverse superviews, I think using a function like the one below is a bit safer.

UITableViewCell *ACMContentViewGetCell(UIView *view)
{
    while ((view = view.superview)) {
        if ([view isKindOfClass:[UITableViewCell class]]) {
            return (UITableViewCell *)view;
        }
    }
    return nil;
}

But that function still assumes contentView is within its cell, which I also didn't see anywhere in the documentation.

So perhaps, the best solution is to rearchitect your code so that you don't need to get cell from contentView, or if you must, then add an instance variable from the subview of contentView to cell.

Upvotes: 1

kubo
kubo

Reputation: 492

ok so the way is to use superview. The superview is component which own the object. If i want get the UITableViewCell from UITextField i used [[UITextField superview] superview].

Upvotes: 0

Related Questions