102 lines
2.4 KiB
Objective-C
Executable File
102 lines
2.4 KiB
Objective-C
Executable File
//
|
|
// HKHTextField.m
|
|
// myhome
|
|
//
|
|
// Created by hkh on 16/9/19.
|
|
//
|
|
//
|
|
|
|
#import "HKHTextField.h"
|
|
#import "Pub.h"
|
|
|
|
@interface HKHTextField()
|
|
|
|
@property (nonatomic) int maxLength; // 可以输入的最大长度.默认值是 INT32_MAX
|
|
@property (nonatomic) BOOL exitOnKeyReturn; // 键盘的 return/done ..etc 按下,是否隐藏键盘。 默认是 true
|
|
@end
|
|
|
|
@implementation HKHTextField
|
|
|
|
// called by code
|
|
- (instancetype)init
|
|
{
|
|
self = [super init];
|
|
if (self) {
|
|
[self customeInit];
|
|
}
|
|
return self;
|
|
}
|
|
|
|
// call when init from storyboard/xib/nib file
|
|
- (instancetype)initWithCoder:(NSCoder *)coder
|
|
{
|
|
self = [super initWithCoder:coder];
|
|
if (self) {
|
|
[self customeInit];
|
|
}
|
|
return self;
|
|
}
|
|
|
|
// called by code
|
|
- (instancetype)initWithFrame:(CGRect)frame
|
|
{
|
|
self = [super initWithFrame:frame];
|
|
if (self) {
|
|
[self customeInit];
|
|
}
|
|
return self;
|
|
}
|
|
|
|
// 自定义属性的初始化
|
|
-(void) customeInit {
|
|
_maxLength = INT32_MAX;
|
|
_exitOnKeyReturn = true;
|
|
// return 按下,键盘隐藏
|
|
[self addTarget:self action:@selector(onEndOnExit) forControlEvents:UIControlEventEditingDidEndOnExit];
|
|
[self addTarget:self action:@selector(onEditingDidBegin) forControlEvents:UIControlEventEditingDidBegin];
|
|
}
|
|
|
|
-(void) setMaxLength:(int)maxLen {
|
|
_maxLength = maxLen;
|
|
// UITextField的最大长度
|
|
[self addTarget:self action:@selector(textDidChanged:) forControlEvents:UIControlEventEditingChanged];
|
|
}
|
|
|
|
/**
|
|
* when textfiled's text did changed, and not end editing, this action will be call.
|
|
* At this moment, wo can check the length.
|
|
**/
|
|
-(void) textDidChanged:(UITextField*)tf {
|
|
if(tf.text.length > _maxLength) {
|
|
tf.text = [tf.text substringToIndex:_maxLength-1];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* enable/disable the software keyboard hide function when user tap the keyboard return key
|
|
*
|
|
**/
|
|
-(void) setExitOnKeyReturn:(BOOL)exit {
|
|
if (exit && self.exitOnKeyReturn) {
|
|
return;
|
|
}
|
|
|
|
if (exit) {
|
|
[self customeInit];
|
|
} else {
|
|
_exitOnKeyReturn = false;
|
|
[self removeTarget:self action:@selector(textDidChanged:) forControlEvents:UIControlEventEditingDidEndOnExit];
|
|
}
|
|
}
|
|
|
|
-(void) onEditingDidBegin {
|
|
NSLog(@"onEditingDidBegin");
|
|
[Pub getApp].activeTextField = self;
|
|
}
|
|
-(void) onEndOnExit {
|
|
[self resignFirstResponder];
|
|
[Pub getApp].activeTextField = nil;
|
|
}
|
|
|
|
@end
|