昨天在群里看到這道面試題,感覺很有意思。今天先挖坑,記錄部分需要考慮的情況,更復雜的條件以后再慢慢填。
我們先考慮cell在tableView中發生了滾動事件的情況。
簡單的方案是監測tableView的滾動事件,然后通過visibleCells屬性判斷cell是否可見。
-
成為某個視圖的子視圖時,先移除之前的kVO,然后對視圖層級中所有class為UIScrollView的contentSize添加KVO
- (void)didMoveToSuperview {
[self unKVO];
UIView *aView = self.superview;while (aView) { if ([aView isKindOfClass:[UIScrollView class]]) { [self observer:aView forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:(void *)__LINE__]; } aView = aView.superview; } }
-
記錄KVO了哪些視圖的,方便及時移除
static NSMutableArray *receiverArr;
static SunTableViewCell *cell;
- (void)observer:(NSObject *)receiver forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context {
if (cell && cell != self) {
return;
}
cell = self;
[receiver addObserver:self forKeyPath:keyPath options:options context:context];
if (!receiverArr) {
receiverArr = [NSMutableArray array];
}
[receiverArr addObject:receiver];
}- (void)dealloc { [self unKVO]; } - (void)unKVO { NSLog(@""); [receiverArr enumerateObjectsUsingBlock:^(id _Nonnull receiver, NSUInteger idx, BOOL *_Nonnull stop) { NSObject *observationInfo = [receiver observationInfo]; NSArray *_observances = [observationInfo valueForKey:@"_observances"]; [_observances enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) { NSObject *observer = [obj valueForKey:@"_observer"]; if ([observer isEqual:self]) { NSString *_property = [obj valueForKeyPath:@"_property._keyPath"]; [receiver removeObserver:self forKeyPath:_property]; } }]; }]; }
-
打印監測到的值變化
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *, id> *)change context:(void *)context {NSLog(@"self:%@ visibleCells:%@", self, [[self tableView] visibleCells]); // 判斷是否在tableView的可見cell內 if (![[[self tableView] visibleCells] containsObject:self]) { NSLog(@"隱藏"); self.textLabel.text = @"隱藏"; NSLog(@"%@", [self tableView]); } else{ NSLog(@"顯示"); self.textLabel.text = @"顯示"; NSLog(@"%@", [self tableView]); } NSLog(@"self:%@ visibleCells:%@", self, [[self tableView] visibleCells]); }
根據我在iPhone5S,iOS8.3上面的實測結果:滿足離屏監測
。
第一種情況測試成功。