2016-08-29 72 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單元格大多滿足非常基本的情況,仍然需要使用這些類型的頁眉或頁腳。 –