Question

I have a UITableView which is made up of my own custom UITableViewCells, subclassed as CustomCell. I add a UITextField to that cell and a method runs on certain events (from the text field).

When this method runs, I need to access the CustomCell that the text field is a subview of.

So I thought, how can I access the parent view of the text field (the CustomCell)?

I have tried this, get the text field, the sender of the method, then from that get its superview.

CustomTextField *textField = sender;
    CustomCell *cell = (CustomCell *)[textField superview];

However this fails, when I try to access a property of my cell, the app crashes and I get this in the console: [UIView myLabel]: unrecognized selector sent to instance. (myLabel is the property I am trying to access on the cell.)

Why doesn't this work, or is there an alternative method of accessing that cell?

Was it helpful?

Solution

You are not supposed to add your views as direct subviews of a UITableViewCell. Instead, you are supposed to add them as subviews of the cell's contentView. If you lay out your cell in a xib, Interface Builder will automatically take care of this for you. So in general you should not expect the cell to be the direct superview of your text field.

I would handle this in one of two ways:

  1. Give CustomTextField a weak property that references its containing CustomCell. Then you can just ask the text field for its cell. If you're using a xib, make the property an IBOutlet and hook it up in the xib. If you're creating the cell in code, set the property in code when you create the cell and the text field.

  2. Walk up the view hierarchy looking for the CustomCell ancestor.

    CustomCell *cell = textField.superview;
    while (cell && ![cell isKindOfClass:[CustomCell class]]) {
        cell = [cell superview];
    }
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top