如何编写自定义UItextField类

如何编写自定义UItextField类

问题描述:

在我的应用程序中,我需要使用大量的文本字段,我真的不希望每个viewcontroller类包含可能很乱的文本字段的委托,我只是想创建一个通用的类来处理它textfields的委托,并返回一个文本字段,我可以将其作为子视图添加到我需要的地方。我想把它作为一个库,每当我需要一个文本字段时调用该类
例如

In my app, i need to use a lot of textfields and i don't really want that every viewcontroller class contains the delegates of textfields which could be messy, I just want to create a generic class where it takes care of the delegate of textfields and returns me a text field where i can add it as a subview where ever i need. I want to make it as a library and call the class whenever i need a textfield FOR example

CustomTexTField *textField = [[CustomTextField alloc] initWithFrame:Frame];
// returns  a textField whose delegate will be set to CustomTextField //
// all i should do is just adding it as a subView //
[self.view addSubView:textField];

这可能吗?
提前致谢!!

Is this possible??. Thanks in advance!!

作为Midhun回答你需要创建一个自定义TextField类并设置委托那个班。喜欢这个

As Midhun Answered you need to create a custom TextField class and also set delegate in that class. Like this

.h FIle


@interface CustomTextField : UITextField<UITextFieldDelegate>
@end


.m文件


@implementation CustomTextField
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.delegate = self;
    }
return self;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField{
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    return YES;
}
@end