您的位置:首页 > 移动开发 > IOS开发

iOS KVC和KVO的使用

2017-03-24 14:59 288 查看
KVC:使用字符串来描述对象需要更改的属性,用来获取或修改对象的属性值。

[Student setValue:@"1234" forKeyPath: @"card.no"];
[Student valueForKeyPath:@"card.no"]


KVO是一种非常重要的机制,用来监听对象属性的变化。

//1.添加观察者
[stu addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];
//2.实现监听方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if([keyPath isEqualToString:@"frame"]) {
NSLog(@"keyPath=%@,object=%@,newValue=%.2f,context=%@",keyPath,object,[[change objectForKey:@"new"] floatValue],context);
}
}
//3.移除监听器
[stu removeObserver:self forKeyPath:@"frame"];


然后用Swift举个例子:监听当前控制器frame的变化修改按钮的frame

init() {
super.init(frame: CGRect.init(x: 0, y: ScreenHeight - 49, width: ScreenWidth, height: 49))
self.addSubview(plusButton)
//KVC赋值
plusButton .setValue(CGPoint.init(x: ScreenWidth / 2, y: 49 - plusButton.bounds.size.height / 2), f
aefc
orKey: "center")
//添加KVO
self .addObserver(self, forKeyPath: "frame", options: .new, context: nil)
}

convenience init(delegate: LAXTabBarDelegate) {
self.init()
self.tabbarDelegate = delegate
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

deinit {
//移除KVO
removeObserver(self, forKeyPath: "frame")
}

//实现KVO
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "frame" {
if let rect = change?[.newKey] as? CGRect {
plusButton .setValue(CGPoint.init(x: rect.size.width / 2, y: 49 - plusButton.bounds.size.height / 2), forKey: "center")
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: