iOS - Implementing a Class for UITextField

做~自己de王妃 提交于 2019-12-06 04:43:56

Yes You Can do this by making a BaseUITextFeild .h and .m file as shown in the following image.

And then Just add the following code regarding your design in BaseUITextFeild.m file

- (void)awakeFromNib {

    [self setupUI];
    [self setKeyboardAppearance:UIKeyboardAppearanceAlert];
}

// Function to setup the common UI throught the app.
- (void)setupUI {
    [self setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    [self setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
    [self setTextAlignment:NSTextAlignmentCenter];
    [self setValue:[UIColor colorWithRed:120.0/225.0 green:120.0/225.0 blue:120.0/225.0 alpha:1.0] forKeyPath:@"_placeholderLabel.textColor"];
    [self setFont:[UIFont boldSystemFontOfSize:15.0f]];
}

Generating a custom UITextField programmatically
And then just import "BaseUITextFeild.h" in the ViewController Where you want to use it.

BaseUITextFeild *field1 = [[BaseUITextFeild alloc] initWithFrame:CGRectMake(135, 292, 50, 20)];
[self addSubview:field1];

Generating a custom UITextField From Interface Builder(Storyboard/.XIB)
Add a UITextfield and then just Change the Class to your Custom TextView Class.

By Applying Following technique you can use this same UITextFeild through out the Application, Just need to import BaseUITextFeild.h.

You can also use this UITextFieldCategory

Follow this Two Example UITextField+withFrame.h and UITextField+ColoredPlaceholder.h. You can also customize you UITextField as per your need.

Manish Agrawal

Create a method

-(UITextField*)createTextFieldWithFrame:(CGRect)frame{
    UITextField *textField = [[UITextField alloc] initWithFrame:frame];
    textField.backgroundColor = [UIColor clearColor];
    textField.borderStyle = UITextBorderStyleNone;
    textField.returnKeyType = UIReturnKeyNext;
    textField.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
    textField.placeholder = @"size";
    [self.view addSubview:textField];
    return textField;
}

for creating multiple textfields call this method

UITextField *text1 = [self createTextFieldWithFrame:CGRectZero];
UITextField *text2 = [self createTextFieldWithFrame:CGRectZero];

You can create a custom xib with the UITextField created as you want and reuse that every time you need.

Or you can subclass UITextField and do the additional setup inside.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!