如何在代码而不是Interface Builder中设置didEndOnExit?

时间:2011-10-14 18:32:08

标签: iphone objective-c ios xcode interface-builder

  

可能重复:
  Assign a method for didEndOnExit event of UITextField

如何在纯代码而不是IB中将didEndOnExit添加到UITextField?

谢谢!

1 个答案:

答案 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;
}