无法让UITextFieldDelegate工作

时间:2013-12-13 13:03:59

标签: ios iphone objective-c

我编写了一个自定义视图CustomViewA : UIView<UITextFieldDelegate>并实现了委托的方法。

在CustomViewA的init中我写道:

- (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;
}

在这个 xib 文件中包含一个 UITextField 控件,我在init方法中设置了它的委托。但是当我运行它并编辑文本字段时,代表的方法是调用。任何人都可以告诉我为什么?我该如何解决?

3 个答案:

答案 0 :(得分:0)

确保UITextField已正确连接到CustomViewA的IBOutlet。 否则,尝试在init中设置委托将无效,

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

答案 1 :(得分:0)

如果你从xib文件初始化一个视图,就不要使用 - (id)init。

并在- (void)awakeFromNib.

中设置您的UITextField的委托方法

答案 2 :(得分:0)

要加载从xib文件中继承UIView的视图,您可以这样做:

// 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;
}

然后在控制器中添加视图:

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

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