如何在纯代码而不是IB中将didEndOnExit添加到UITextField?
谢谢!
答案 0 :(得分:4)
假设您在谈论textFieldDidEndEditing:
或textFieldShouldReturn:
。您可以在视图控制器中实现该方法,并将文本字段delegate
设置为self
,如下所示:
- (void)viewDidLoad {
[super viewDidLoad];
// ....
myTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 50, 25)];
myTextField.delegate = self;
[self.view addSubview:myTextField];
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
if (textField == myTextField) {
// Do stuff...
}
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField == myTextField) {
return YES;
}
return NO;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ((myTextField.text.length + string.length) < 5) {
return YES;
}
return NO;
}
然后,在@interface
的标题文件中,您可以指定您是UITextFieldDelegate
,如下所示:
@interface MyViewController : UIViewController <UITextFieldDelegate> {
// ....
UITextField *myTextField;
// ....
}
// Optionally, to make myTextField a property:
@property (nonatomic, retain) UITextField *myTextField;
@end
UITextField Reference
UITextFieldDelegate Reference
编辑(根据你的评论,这应该有效):
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ((myTextField.text.length + string.length) < 5) {
return YES;
}
return NO;
}