2016-08-29 140 views
4

我正在尝试为待办事项列表类型的应用程序制作详细屏幕。下面是详细当前屏幕上的样子:自动调整UICollectionView标题

detail screen

这是一个UICollectionViewController,一个头。标题包含2个UILabel对象和一个UITextView对象。这些对象的布局由垂直UIStackView进行管理。 A UIView用于设置白色背景。

我在运行时定义此UICollectionReusableView的高度时遇到了一些困难。任何建议表示赞赏。

+0

http://stackoverflow.com/a/33696385/6064629也许它会帮助你。 – Himanshu

+0

谢谢@himanshu。我仍然希望有比这更好的答案,因为该解决方案基本上实例化了一个额外的'UICollectionReusableView'副本,并在之后立即抛出它。 –

+0

@KelvinLau你设法弄清楚什么?我不是所提供解决方案的忠实粉丝,因为它需要XIB文件。 – Michael

回答

0

下面是如何处理自定义UICollectionViewReusableView与自动布局没有XIB文件。

  1. 执行referenceSizeForHeaderInSection委托方法。
  2. 在其中,实例化您用作标题视图的视图。
  3. 将其可见性设置为隐藏,以避免闪烁。
  4. 将视图添加到collectionview的超级视图。
  5. 使用自动布局设置它的布局,以匹配标题的预期视觉效果。
  6. 调用setNeedsLayoutlayoutIfNeeded
  7. 从上海华删除视图

注意:我不是这个解决方案的大风扇,因为它每次添加自定义视图到的CollectionView的上海华,执行计算。虽然我没有注意到任何性能问题。

小心#2:我会将其视为临时解决方案,并在发布后迁移到自我尺寸补充视图。

我使用PureLayout进行自动布局。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { 

    let header = CustomHeaderView() 

     header.isHidden = true; 
     self.view.addSubview(header) 
     header.autoPinEdge(toSuperviewEdge: .leading) 
     header.autoPinEdge(toSuperviewEdge: .trailing) 
     header.autoPin(toTopLayoutGuideOf: self, withInset: 0) 
     header.setupHeader(withData: self.data) 
     header.setNeedsLayout() 
     header.layoutIfNeeded() 
     header.removeFromSuperview() 

     return header.frame.size 
} 
1

这是一个黑客,但似乎工作。

// showhere to keep a reference 
UICollectionReusableView * _cachedHeaderView; 


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{ 

    if(!_cachedHeaderView){ 
     // dequeue the cell from storyboard 
     _cachedHeaderView = [collectionView dequeueReusableCellWithReuseIdentifier:[NSString stringWithFormat:@"header_cell"] forIndexPath:indexPath]; 

     // set captions/images on the header etc... 

     // tell the collectionview to redraw this section 
     [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]]; 
    } 

    return _cachedHeaderView; 
} 


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{ 

    // once there is a reference ot the view, use it to figure out the height 
    if(_cachedHeaderView){ 
     return [_cachedHeaderView systemLayoutSizeFittingSize:collectionView.bounds.size withHorizontalFittingPriority:UILayoutPriorityRequired verticalFittingPriority:UILayoutPriorityDefaultLow]; 

    } 

    // a placeholder value just to get the dequeueReusableCellWithReuseIdentifier to work 
    return CGSizeMake(collectionView.bounds.size.width, 100); 
} 
+0

看起来,Self-Sizing单元格大多满足非常基本的情况,仍然需要使用这些类型的页眉或页脚。 –