美文网首页
cell怎么知道自己不在屏幕中了?(1)

cell怎么知道自己不在屏幕中了?(1)

作者: 酷酷的哀殿 | 来源:发表于2016-03-10 15:54 被阅读3286次

昨天在群里看到这道面试题,感觉很有意思。今天先挖坑,记录部分需要考虑的情况,更复杂的条件以后再慢慢填。

我们先考虑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上面的实测结果:满足离屏监测
第一种情况测试成功。

相关文章

网友评论

      本文标题:cell怎么知道自己不在屏幕中了?(1)

      本文链接:https://www.haomeiwen.com/subject/baftlttx.html