开发者

How can I set didEndOnExit in code rather than Interface Builder? [duplicate]

开发者 https://www.devze.com 2023-04-13 07:01 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: Assign a method for didEndOnExit event of UITextField
This question already has answers here: Closed 10 years ago.

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号