在自定义UIView和UIViewController中同时使用相同的UITextFieldDelegate方法

时间:2014-04-17 02:38:36

标签: ios uitextfield appdelegate uitextfielddelegate

我有一个UIView(名为HCTextFieldView),上面有子视图:UITextFieldUILabel

UITextField's代表等于自我。委托方法textFieldDidBeginEditingtextFieldDidEndEditing执行文本字段的背景突出显示效果。

接下来我在我的UIView中使用了这个自定义UIViewController(HCTextFieldView)。要处理工具栏中的“下一步”和“上一页”按钮的操作(附在文本字段的键盘上方),我需要在UIViewController中使用相同的文本字段委托方法,但是代表被覆盖。

**@interface HCBaseTextField : UIView <UITextFieldDelegate>**
...
@end

**@implementation HCBaseTextField {}**

...

textField = [[UITextField alloc] initWithFrame:CGRectMake(0, titleLabel.bottom, self.width - 20, self.height - titleLabel.height)];
**textField.delegate = self**;

...

#pragma mark - UITextField delegate

//textFieldBG - UIImageView that act as background

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [textFieldBg setImage:[[UIImage imageWithName:@"btn_vvod_medium_act"] stretchableImageWithLeftCapWidth:10 topCapHeight:10]];
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    [textFieldBg setImage:[[UIImage imageWithName:@"btn_vvod_medium_norm"] stretchableImageWithLeftCapWidth:10 topCapHeight:10]];
    return YES;
}

...

@end


**ViewController : UIViewController**

...

HCTextFieldView *textFieldView = [[HCTExtFieldView alloc] init];
textFieldView.textField.delegate = self;

...

//I need to use this methods too but they override previous in UIView delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self.keyboardControls setActiveField:textField];
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [self.keyboardControls setActiveField:textView];
}

1 个答案:

答案 0 :(得分:6)

delegate中设置HCBaseTextField

在HCBaseTextField.h 中添加属性

@property (nonatomic, assign) id<UITextFieldDelegate> textFieldDelagate;

并在 HCBaseTextField.m

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

    ....
    if (self.textFieldDelagate && [self.textFieldDelagate respondsToSelector:@selector(textFieldShouldBeginEditing:)]) {
        [self.textFieldDelagate textFieldShouldBeginEditing:textField];
    }
    return YES;
}

- (void) textFieldDidBeginEditing:(UITextField *)textField {
    ....

    if (self.textFieldDelagate && [self.textFieldDelagate respondsToSelector:@selector(textFieldDidBeginEditing:)]) {
        [self.textFieldDelagate textFieldDidBeginEditing:textField];
    }
}

... //Other delegate methods if needed

并在 ViewController:UIViewController

...

HCTextFieldView *textFieldView = [[HCTExtFieldView alloc] init];

textFieldView.textFieldDelagate = self;

...

并实现委托方法。

- (void) textFieldDidBeginEditing:(UITextField *)textField {
    ....

    //Do the stuff
}