0
votes

I write a custom view CustomViewA : UIView<UITextFieldDelegate>and implements the delegate's methods.

And in the CustomViewA's init I write:

- (id)initWithFrame:(CGRect)frame {
    self = [[[NSBundle mainBundle] loadNibNamed:@"CustomViewA" owner:self options:nil] objectAtIndex:0];
    if (self) {
        //the txtfieldA is a IBOutlet property linked to the nib file.
        self.txtfieldA.delegate = self; //not work
    }
    return  self;
}

And in this xib file includes a UITextField control which I set its delegate in the init method.But when I run this and edit the textfield, the delegate's methods are not called.Can anyone tell me why? And how can I fix it??

3
Please post your entire init method - Andy Obusek
Also, please post the code that creates and uses CustomViewA - Andy Obusek
I've add them, thanks - Rocky

3 Answers

0
votes

Ensure that that the UITextField is correctly wired to the IBOutlet of of CustomViewA. Otherwise, attempting to set the delegate in init will do nothing,

//if self.myTextField is nil, then this does nothing
self.myTextField.delegate = self;
0
votes

just simply do not use -(id)init if you init a view from xib files.

and set your UITextField's delegate method in - (void)awakeFromNib..

0
votes

To load a view which subclass an UIView from a xib file, you can do this way:

// Reusable method to load a class which subclass UIView from a xib.
+ (id)loadNibNamed:(NSString *)nibName ofClass:(Class)objClass andOwner:(id)owner {
    if (nibName && objClass) {
        NSArray *objects = [[NSBundle mainBundle] loadNibNamed:nibName owner:owner options:nil];

        for (id currentObject in objects ){
            if ([currentObject isKindOfClass:objClass])
                return currentObject;
        }
    }

    return nil;
}

Then add the view in your controller:

myCustomViewA = [self loadNibNamed:@"customviewA" ofClass:[CustomViewA class] andOwner:self];

myCustomViewA.delegate = self; // Or do this in the xib file
[self.view addSubview:myCustomViewA];