看下面的代码
//设置眼睛
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"];
}
本文探讨了iOS开发中使用KVO(Key-Value Observing)来观察UI元素的变化,并根据眼睛图标按钮的状态调整文本框宽度的方法。文章还讨论了KVO的一个潜在问题及其解决策略。
773

被折叠的 条评论
为什么被折叠?



