How can I set didEndOnExit in code rather than Interface Builder? [duplicate]
Possible Duplicate:
Assign a method for didEndOnExit event of UITextField
How can I add didEndOnExit to a UI开发者_StackOverflow社区TextField in pure code rather than IB?
Thanks!
Assuming your talking about textFieldDidEndEditing:
or textFieldShouldReturn:
. You would implement the method in your view controller, and set the text fields delegate
to self
like so:
- (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;
}
Then, in your header file in the @interface
you can specify that you are a UITextFieldDelegate
like this:
@interface MyViewController : UIViewController <UITextFieldDelegate> {
// ....
UITextField *myTextField;
// ....
}
// Optionally, to make myTextField a property:
@property (nonatomic, retain) UITextField *myTextField;
@end
UITextField Reference
UITextFieldDelegate Reference
Edit (as per your comment, this should work):
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ((myTextField.text.length + string.length) < 5) {
return YES;
}
return NO;
}
精彩评论