iOS KVC和KVO的使用
2017-03-24 14:59
288 查看
KVC:使用字符串来描述对象需要更改的属性,用来获取或修改对象的属性值。
KVO是一种非常重要的机制,用来监听对象属性的变化。
然后用Swift举个例子:监听当前控制器frame的变化修改按钮的frame
[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") } } }
相关文章推荐
- iOS:KVO/KVC 的概述与使用
- iOS KVC与KVO的简单使用
- iOS--kvo&kvc的使用
- 【iOS】KVC 和 KVO 的使用场景
- iOS:KVO/KVC 的概述与使用
- 【iOS】KVC 和 KVO 的使用场景
- IOS开发 - KVC和KVO的使用
- iOS:KVO/KVC 的概述与使用
- 【iOS】KVC 和 KVO 的使用场景
- iOS:KVO/KVC 的概述与使用
- iOS开发中KVO & KVC的使用
- 【iOS】KVC 和 KVO 的使用场景
- iOS-KVC和KVO的使用
- 【iOS】KVC 和 KVO 的使用场景
- iOS:KVO/KVC 的概述与使用
- iOS:KVO/KVC 的概述与使用
- iOS:KVO/KVC 的概述与使用
- 【iOS】KVC 和 KVO 的使用场景
- 【iOS】KVC 和 KVO 的使用场景
- ios KVC KVO的使用