-
先上效果图
屏幕快照 2018-08-16 下午3.50.45.png -
WLTextField.h
#import <UIKit/UIKit.h>
@protocol WLTextFieldDelegate<NSObject>
// 获取输入框内的值
-(void)wlTextFieldDidChange:(NSString *)text;
@end
@interface WLTextField : UIView<UITextFieldDelegate>
@property(nonatomic,strong)UIView *underLine; // 下划线
@property(nonatomic,weak)id<WLTextFieldDelegate> delegate;
@end
- WLTextField.m
#import "WLTextField.h"
@implementation WLTextField
-(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height - 11)];
textField.placeholder = @"请输入充电桩编号";
textField.borderStyle = UITextBorderStyleNone;
textField.delegate = self;
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
[self addSubview:textField];
_underLine = [[UIView alloc] initWithFrame:CGRectMake(0, frame.size.height - 1, frame.size.width, 1)];
_underLine.backgroundColor = [UIColor grayColor];
[self addSubview:_underLine];
}
return self;
}
#pragma TextField private method
-(void)textFieldDidChange:(UITextField *)textField
{
if (self.delegate && [self.delegate respondsToSelector:@selector(wlTextFieldDidChange:)]) {
[self.delegate wlTextFieldDidChange:textField.text];
}
// NSLog(@"内容 : %@",textField.text);
}
#pragma UITextFieldDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
_underLine.backgroundColor = [UIColor greenColor];
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
_underLine.backgroundColor = [UIColor grayColor];
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// 四位加一个空格
if ([string isEqualToString:@""]) { // 删除字符
if ((textField.text.length - 2) % 5 == 0) {
textField.text = [textField.text substringToIndex:textField.text.length - 1];
}
} else {
if (textField.text.length % 5 == 0) {
textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
}
}
return YES;
}
- 实现文件 实现代理
WLTextField *textField = [[WLTextField alloc] initWithFrame:CGRectMake(20, 84, 200, 30)];
textField.delegate = self;
[self.view addSubview:textField];
#pragma mark WLTextFieldDelegate
-(void)wlTextFieldDidChange:(NSString *)text
{
NSLog(@"我的内容 : %@",text);
}
网友评论