[英]How can I get UITextFieldDelegate.shouldChangeCharactersInRange to fire with custom inputView?
[英]Can't get UITextFieldDelegate to work
我編寫了一個自定義視圖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
設置了它的委托,但是當我運行它並編輯文本字段時, 沒有調用該委托的方法,有人可以告訴我為什么嗎? 我該如何解決呢?
確保將UITextField
正確連接到CustomViewA的IBOutlet
。 否則,嘗試將委托設置為init
不會做任何事情,
//if self.myTextField is nil, then this does nothing
self.myTextField.delegate = self;
如果您從xib文件初始化視圖,只是根本不使用-(id)init。
並在- (void)awakeFromNib.
設置UITextField的委托方法- (void)awakeFromNib.
。
要從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];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.