看下面的代码
//设置眼睛
UIButton *button= [[UIButton alloc]initWithFrame: (CGRect){{self.width - self.height,0},{self.height,self.height}}];
button.backgroundColor = [UIColor redColor];
[button addTarget:self action:@selector(changePassWord) forControlEvents:UIControlEventTouchUpInside];
self.eyeButton = button;
self.eyeButton.hidden = YES;
//注册监听者
[self.eyeButton addObserver:self forKeyPath:@"hidden" options:NSKeyValueObservingOptionNew context:nil];
[self addSubview:button];
#pragma mark - 设置眼睛,如果设置的眼睛是显示状态那么就要进行textField的宽度减少
/**
* 监听者的响应者事件
*
* @param keyPath hidden
* @param object button
* @param change 值如果进行改变
* @param context
*/
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if ([keyPath isEqualToString:@"hidden"] && object == self.eyeButton ) {
_textField.width = self.eyeButton.x - pixw(6);
_placeHolderLabel.width = _textField.width ;
}
else
[super observeValueForKeyPath:keyPath ofObject:object change:change context: context];
}
-(void)dealloc
{
[self.eyeButton removeObserver:self forKeyPath:@"hidden"];
}