Search code examples
iosiphoneobjective-cuitextfielduitextfielddelegate

UITextFieldDelegate of nested UITextFields not being called


I have a subclass of a UIView (MyView) that has some UITextField as subviews. MyView implements the UITextFieldDelegate protocol in order to be notified when the textfields are clicked. This was working well. Now I need to place the textfields in a sort of "container" to be able to fade in and out this container (and all its children) with an UIView animation. So I created a UIView (MySubview), made it subview of MyView and placed all textfields inside of it. The animation works fine but the UITextFieldDelegate doesn't get called anymore. I think it's because the textfields are not direct children of MyView anymore. Is there any other ways to deal with this?

UPDATE

I did a small version of my code, maybe this helps to find the problem:

@interface MyView : UIView <UITextFieldDelegate>


@implementation MyView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        // This is MySubview:
        UIView *tempLabelsContainer = [[UIView alloc] initWithFrame:self.bounds];
        [tempLabelsContainer setUserInteractionEnabled:YES];
        [self addSubview:tempLabelsContainer];
        self.labelsContainer = tempLabelsContainer;
        [tempLabelsContainer release];

        UITextField *aTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
        [aTextField setBackgroundColor:[UIColor clearColor]];
        [aTextField setText:@"Some text"];
        [aTextField setTag:1];
        [aTextField setDelegate:self];
        [self.labelsContainer addSubview:aTextField];
        [aTextField release];

        // More labels are being added
    }

    return self;
}

#pragma mark - UITextFieldDelegate methods

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    // This is not being called
    NSLog(@"TextField with the tag: %d should be edited", [textField tag]);    

    return NO;
}

Solution

  • I will answer my own question just in case someone happens to have this same problem - difficult to imagine someone doing such silly mistake, though:

    I was setting the frame of the labels container to self.bounds. But the MyViewController was creating MyView with a frame of CGRectZero! I did that change to support animation at the same time I added the container. Therefore I thought that the problem had to do with the view hierarchy. Shame on me!!!

    Anyway, thanks to all helpers, especially to Madhumal Gunetileke who, with his answer, made me watch in a different direction.