ios – 将子视图添加到占用整个单元格框架的UICollectionViewCell

前端之家收集整理的这篇文章主要介绍了ios – 将子视图添加到占用整个单元格框架的UICollectionViewCell前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图将一个UIView添加到占用整个单元框架的UICollectionViewCell.我现在的代码显示在左上角的单个单元格(我怀疑每个单元格在彼此之间都有层叠).我该怎么做?

我计划稍后再次分类UIView,以便自定义添加到单元格的视图.我不想根据我将使用它的方式子类化UICollectionViewCell.

  1. #pragma mark - Collection view data source
  2.  
  3. -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
  4. return 1;
  5. }
  6.  
  7. -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
  8. return 6;
  9. }
  10.  
  11. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  12. {
  13. UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
  14.  
  15. UIView *menuItem = [[UIView alloc] init];
  16. menuItem.frame = cell.frame;
  17. menuItem.backgroundColor = [UIColor greenColor];
  18. [cell addSubview:menuItem];
  19.  
  20. return cell;
  21. }
  22.  
  23. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath; {
  24. return CGSizeMake(60,60);
  25. }

解决方法

你需要使用边界,而不是框架.如果你不知道两者之间的区别,或者为什么这么重要,你应该阅读这个,并在进一步了解之前对它进行理解:
  1. menuItem.frame = cell.bounds;

您还需要设置自动调整掩码,因为单元格最初不会处于正确的大小:

  1. menuItem.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

而且,真的,你应该把它添加到单元格的contentView属性中:

  1. [cell.contentView addSubview:menuItem];
  2. menuItem.frame = cell.contentView.bounds;

也就是说,如果您打算在menuItem中添加大量子视图,我建议对UICollectionViewCell进行子类化,而不是尝试在您的cellForItemAtIndexPath:方法中构建它.如果将布局和设置封装在不同的类中,则可以更容易地进行控制,您可以通过覆盖layoutSubviews来响应高度/宽度更改.

猜你在找的iOS相关文章