看下面的代碼
//設(shè)置眼睛
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;
//注冊(cè)監(jiān)聽者
[self.eyeButton addObserver:self forKeyPath:@"hidden" options:NSKeyValueObservingOptionNew context:nil];
[self addSubview:button];
#pragma mark - 設(shè)置眼睛,如果設(shè)置的眼睛是顯示狀態(tài)那么就要進(jìn)行textField的寬度減少
/**
*? 監(jiān)聽者的響應(yīng)者事件
*
*? @param keyPath hidden
*? @param object? button
*? @param change? 值如果進(jìn)行改變
*? @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"];
}
潛在的問題有可能出現(xiàn)在dealloc中對(duì)KVO的注銷上。KVO的一種缺陷(其實(shí)不能稱為缺陷,應(yīng)該稱為特性)是,當(dāng)對(duì)同一個(gè)keypath進(jìn)行兩次removeObserver時(shí)會(huì)導(dǎo)致程序crash,這種情況常常出現(xiàn)在父類有一個(gè)kvo,父類在dealloc中remove了一次,子類又remove了一次的情況下。不要以為這種情況很少出現(xiàn)!當(dāng)你封裝framework開源給別人用或者多人協(xié)作開發(fā)時(shí)是有可能出現(xiàn)的,而且這種crash很難發(fā)現(xiàn)。