我编写了一个自定义视图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控件,当我运行它并编辑textfield时,我在init method.But中设置了它的委托,委托的方法是而不是 called.Can,有人告诉我为什么吗?我怎样才能修好它?
发布于 2013-12-13 13:55:57
要从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];发布于 2013-12-13 13:21:18
确保UITextField被正确地连接到IBOutlet of CustomViewA。否则,尝试在init中设置委托将一无所获,
//if self.myTextField is nil, then this does nothing
self.myTextField.delegate = self;发布于 2013-12-13 13:22:35
只要从xib文件中输入视图,就不要使用-(id)init。
并在- (void)awakeFromNib.中设置UITextField的委托方法。
https://stackoverflow.com/questions/20567251
复制相似问题