这个问题在这里已经有了答案:
Best Answer-推荐答案 strong>
假设您谈论的是 textFieldDidEndEditing:
或 textFieldShouldReturn:
。您将在 View Controller 中实现该方法,并将文本字段 delegate
设置为 self
,如下所示:
- (void)viewDidLoad {
[super viewDidLoad];
// ....
myTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 50, 25)];
myTextField.delegate = self;
[self.view addSubview:myTextField];
}
- (void)textFieldDidEndEditingUITextField *)textField {
if (textField == myTextField) {
// Do stuff...
}
}
- (BOOL)textFieldShouldReturnUITextField *)textField {
if (textField == myTextField) {
return YES;
}
return NO;
}
- (BOOL)textFieldUITextField *)textField shouldChangeCharactersInRangeNSRange)range replacementStringNSString *)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)textFieldUITextField *)textField shouldChangeCharactersInRangeNSRange)range replacementStringNSString *)string {
if ((myTextField.text.length + string.length) < 5) {
return YES;
}
return NO;
}
关于iphone - 如何在代码而不是 Interface Builder 中设置 didEndOnExit?,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/7771985/