本文中我是想讓一個collectionview内容變化時高度跟随變化,第二步取值時是需要注意的
1.監聽
[selectedColl addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
2.實作 observeValueForKeyPath方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
NSLog(@"keyPath:%@ object:%@ change%@ context%@", keyPath, object, change, context);
//NSConcreteValue
id value = [object valueForKey:keyPath];
NSAssert([value isKindOfClass:[NSValue class]],
@"監聽到的value不是NSValue類型");
NSAssert(strcmp(@encode(CGSize), [value objCType]) == 0,
@"監聽到的value不是CGSize類型");
//取出value
CGSize unwrappedValue;
[value getValue:&unwrappedValue];
selectedH.constant = unwrappedValue.height;
}
取值方法來自于https://stackoverflow.com/questions/4615966/what-is-an-nsconcretevalue-and-how-do-i-extract-its-value
3.頁面銷毀時移除監聽
- (void)dealloc {
[selectedColl removeObserver:self forKeyPath:@"contentSize"];
NSLog(@"頁面銷毀");
}
完