簡體   English   中英

正確使用包含UICollectionView的UITableViewCell的正確方法

[英]Proper way to reuse UITableViewCell containing UICollectionView

我有一個UITableView。 每個單元格包含水平集合視圖。 當我滾動表格時,集合視圖包含過多的單元格。 我猜這是因為這些單元未正確復用。 在圖示中,灰色單元格不應該存在。 表格視圖

我應該在reuseCell中放入正確的代碼是什么? 我嘗試了以下操作,但導致應用崩潰

過度

ride func prepareForReuse()
    {
        super.prepareForReuse()
        channelsCollectionView = UICollectionView()
    }

它應該是

//Reset the datasource
channelsCollectionView.dataSourceArray = []()

//Reload data of collectionView
channelsCollectionView.reloadData()

再次取決於它,這是一種方法

請按照以下步驟操作。 在UITableViewCell內,CollectionView可以很好地工作。

  1. 像這樣使UICollectionView的子類。

     @interface MyCollectionView : UICollectionView <UICollectionViewDataSource, UICollectionViewDelegate> /* Properties */ @property (nonatomic, strong) NSMutableArray *imagesArray; @end 
  2. 在您的MyCollectionView .m文件中

     @interface MyCollectionView () @property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout; @end @implementation MyCollectionView -(void)awakeFromNib { [super awakeFromNib]; self.dataSource = self; self.delegate = self; //Set CollectionView Layout [self setCollectionViewLayout:self.flowLayout]; } #pragma mark - CollectionView DataSource methods - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{ return 1; } -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{ return _imagesArray.count; } -(UICollectionViewFlowLayout *)flowLayout{ // set your layout here _flowLayout = [[UICollectionViewFlowLayout alloc] init]; [_flowLayout setSectionInset:UIEdgeInsetsMake(topSpacing, leftMargin, bottomSpacing, rightMargin)]; [_flowLayout setMinimumInteritemSpacing:cellSpacing]; [_flowLayout setMinimumLineSpacing:lineSpacing]; [_flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal]; [_flowLayout setItemSize:CGSizeMake(cellWidth, cellHeight)]; return _flowLayout; } #pragma mark - setter method -(void)setImagesArray:(NSMutableArray *)imagesArray { _imagesArray = imagesArray; [self reloadData]; } -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { // configure cell here } 
  3. 在您的ViewController .m中具有UITableView

      - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { MyTableViewCell *cell = (MyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"CellIdentifier" forIndexPath:indexPath]; cell.myCollectionView.imagesArray = //Array here return cell; } 
  4. 您需要在TableViewCell中設置collectionView的固定高度。 由於您具有水平collectionView。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM