看下面的代码
//设置眼睛
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"];
}
潜在的问题有可能出现在dealloc中对KVO的注销上。KVO的一种缺陷(其实不能称为缺陷,应该称为特性)是,当对同一个keypath进行两次removeObserver时会导致程序crash,这种情况常常出现在父类有一个kvo,父类在dealloc中remove了一次,子类又remove了一次的情况下。不要以为这种情况很少出现!当你封装framework开源给别人用或者多人协作开发时是有可能出现的,而且这种crash很难发现。