需求:
一個密碼框的UITextField:
默認(rèn) 展示 ****
不編輯時候 展示 ***
編輯時候正常
自定義控件
1.創(chuàng)建一個類,繼承UITextField
.h 中添加屬性
@property(nonatomic,strong)NSString *actualText;
.m 初始化時趾疚,添加監(jiān)聽方法
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if(self) {
self.showText = @"********";
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(begingEdit) name:UITextFieldTextDidBeginEditingNotification object:self]; //通知:監(jiān)聽
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeEdit) name:UITextFieldTextDidChangeNotification object:self]; //通知:監(jiān)聽
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endEdit) name:UITextFieldTextDidEndEditingNotification object:self]; //通知:監(jiān)聽
}
return self;
}
添加實現(xiàn)方法
開始輸入的時候
-(void)begingEdit{
self.text = @"";
if (self.actualText != nil && ![self.actualText isEqualToString:@""]) {
// 恢復(fù)
self.text = self.actualText;
}
}
結(jié)束輸入
-(void)endEdit{
self.actualText = [self.text copy];
self.text = @"*******";
}
這樣可以實現(xiàn)需要的效果,但是只有屬性actualText
是正確的值,而text
的數(shù)據(jù)是錯誤的。想優(yōu)化一下:
text
的數(shù)據(jù)是正確的钥弯,對于使用者,不需要關(guān)心actualText
我嘗試了
·添加BOOL的成員變量
·添加string的屬性
·重寫-get
督禽,-set
方法發(fā)現(xiàn)
當(dāng)編輯脆霎,或者完成編輯時
-(NSString *)text{
if (isEdit) {
return _tempText;
}
return self.actualText;
}
改方法無法正確返回實際的text值。
如有人能夠解決此問題狈惫,歡迎討論睛蛛,感激不盡
添加一個控件
上面的方法走不通就只能換一個寫法。
添加一個Label 來模擬******
簡單粗暴:
-(UILabel *)showLabel{
if (!_showLabel) {
_showLabel = [[UILabel alloc]init];
_showLabel.backgroundColor = self.backgroundColor;
_showLabel.text = @"******";
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(touchLabel)];
[_showLabel addGestureRecognizer:tap];
}
return _showLabel;
}
// 點擊模擬視圖
-(void)touchLabel{
_showLabel.hidden = YES;
}
-(void)layoutSubviews{
[super layoutSubviews];
CGFloat X = self.leftView.frame.size.width ;
CGFloat W = self.frame.size.width - self.leftView.frame.size.width - self.rightView.frame.size.width;
self.showLabel.frame = CGRectMake(X, 1, W, self.frame.size.height-2);
[self addSubview:self.showLabel];
}
注:
1.不能再initWithFrame:
中添加Label 會有問題
2.注意Label的位置胧谈,考慮UITextField的左右視圖
-(void)begingEdit{
_showLabel.hidden = YES;
}
-(void)endEdit{
_showLabel.hidden = NO;
}