// 懒加载  UICollectionView

- (UICollectionView *)myCollectionView {

    if (!_myCollectionView) {

        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];

        CGFloat width   = GET_SCREEN_WIDTH-(isPad?82:0);

        CGFloat height  = GET_SCREEN_HEIGHT-(64+(isPad?20:0));

        self.myCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, width, height) collectionViewLayout:flowLayout];

        _myCollectionView.backgroundColor = [UIColor clearColor];

        _myCollectionView.scrollEnabled = false;

        _myCollectionView.delegate = self;

        _myCollectionView.dataSource = self;

        

//        _myCollectionView.contentInset = UIEdgeInsetsMake(64, 0, 20, 0);

//        _myCollectionView.userInteractionEnabled = NO;

        [self registerMyCell];

        [self p_registerObserve];

    }

    return _myCollectionView;

}

 

 

#pragma mark - KVO

- (void)p_registerObserve {

    if (_myCollectionView) {

        [_myCollectionView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:kCollectionViewContentSizeContext];

    }

}

 

- (void)p_deregisterObserve {

    // 这里不使用点语法触发懒加载,因为可能在这里才触发懒加载创建collectionView,此时还没有添加观察者

    // 如果这时移除观察者很可能会造成崩溃

    if (_myCollectionView) {

        [_myCollectionView removeObserver:self forKeyPath:@"contentSize" context:kCollectionViewContentSizeContext];

    }

}

 

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {

    if (context == kCollectionViewContentSizeContext) {        

        CGSize contentSize = [change[NSKeyValueChangeNewKey] CGSizeValue];

        CGFloat width   = GET_SCREEN_WIDTH-(isPad?82:0);

        self.myCollectionView.frame = CGRectMake(0, 0, width, contentSize.height);

        self.baseTableView.tableFooterView = self.myCollectionView;

    }

}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-24
  • 2021-06-18
  • 2022-12-23
  • 2021-08-11
猜你喜欢
  • 2022-01-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案