Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a Custom UItextField Class

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!!

like image 866
Vijay Avatar asked Jul 10 '13 04:07

Vijay


People also ask

What is a UITextField?

An object that displays an editable text area in your interface.

What is TextField in Swift?

A TextField is a type of control that shows an editable text interface. In SwiftUI, a TextField typically requires a placeholder text which acts similar to a hint, and a State variable that will accept the input from the user (which is usually a Text value).


2 Answers

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 File

@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
like image 86
Manish Agrawal Avatar answered Sep 25 '22 13:09

Manish Agrawal


Create a subclass of UITextField and use it.

@interface CustomTexTField : UITextField
@end

@implementation CustomTexTField

//Add the stuffs here

@end

wherever you need the text field you can use:

CustomTexTField *textField = [[CustomTextField alloc] initWithFrame:customFrame];
[self.view addSubView:textField];
like image 43
Midhun MP Avatar answered Sep 26 '22 13:09

Midhun MP