TableCell加UICollectionView
- 小伙伴們很多時候在實現(xiàn)界面的時候,或多或少在TableCell上面加一些可以橫向滑動的圖片,怎么實現(xiàn)呢?
- 很多小伙伴第一想到的是用XIB貼一個Scrollview上去不就行了,話說的沒錯,但是怎么解決最表層tablecell復(fù)用的問題呢?在tablecell上加scrollview如果貼的圖片數(shù)量不定,有時一張有時兩張甚至更多!這時令人尿頻的tablecell復(fù)用機制來了。他會重疊或者覆蓋之前元素少的那一個Cell。導(dǎo)致畫面的混亂,達不到我們想要的對應(yīng)效果。
好了進入正題直接上關(guān)鍵代碼
-
這是視圖控制器里面的代碼
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
CollectionTableCell *cell =[tableView dequeueReusableCellWithIdentifier:cell_dentifier forIndexPath:indexPath];
cell.dataArr =_dataArray[indexPath.row];
cell.fuckButton.tag =indexPath.row;
[cell.fuckButton addTarget:self action:@selector(fuckAction:) forControlEvents:UIControlEventTouchUpInside];
[cell.fuckButton setTitle:[NSString stringWithFormat:@"fuck%ld",indexPath.row] forState:0];
return cell;
}
Paste_Image.png
Paste_Image.png
這是tableCell里面的代碼
- (void)setSelected:(BOOL)selected animated: (BOOL)animated {
[super setSelected:selected animated:animated];
_myCollectionView.delegate =self;
_myCollectionView.dataSource =self;
_myCollectionView.backgroundColor =[UIColor clearColor];
_withScroll =_myCollectionView.contentSize.width;
_collectionWith= _myCollectionView.frame.size.width;
//這里是實現(xiàn)一個效果當(dāng)他滑動范圍超出UIcollectionView讓他可以用戶交互,
反之不能交互,這樣可以實現(xiàn)一個點擊效果!集合視圖能滑動讓他滑動,
不能滑動可以失去交互后點擊可以實現(xiàn)tableCell點擊事件
if (_withScroll>_collectionWith) {
_myCollectionView.userInteractionEnabled =YES;
NSLog(@"yes");
}else{
_myCollectionView.userInteractionEnabled=NO;
}
NSLog(@"size=%f",_withScroll);
UICollectionViewFlowLayout *layout =(UICollectionViewFlowLayout *)_myCollectionView.collectionViewLayout;
layout.scrollDirection =UICollectionViewScrollDirectionHorizontal;
layout.itemSize =CGSizeMake(WIDTH/4, 100);
[_myCollectionView setCollectionViewLayout:layout];
[_myCollectionView registerNib:[UINib nibWithNibName:@"MyCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"MyCollectionCell"];
// Configure the view for the selected state
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return _dataArr.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
MyCollectionCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"MyCollectionCell" forIndexPath:indexPath];
cell.PhotoView.image =[UIImage imageNamed:_dataArr[indexPath.row]];
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
}
-(void)setDataArr:(NSMutableArray *)dataArr{
_dataArr =dataArr;
- 注意這個刷新視圖尤其重要,它可以成功破解外層TabelViewcell的復(fù)用機制。如果當(dāng)初把UIcollectionView換成UIScrollView的話,它拿到數(shù)據(jù)是不能刷新視圖。很難解決復(fù)用問題,而集合視圖做到了!
[_myCollectionView reloadData];
} - 以上便是tableCell上放集合視圖的例子。其實Cell上可以放任何視圖,比如輪播圖之類的。只要是UIview的之類就行。我上次把輪播圖放在了UIcollectionView的header上,效果也不錯。因為header和footer是不被復(fù)用的,可以解決我們不想復(fù)用的事件!

